我想将ajax调用值返回给其他函数。代码如下所示
脚本
var obj2 = ajax_call();
function ajax_call() {
var obj3;
$.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
obj3 = $.parseJSON(data);
});
return(obj3);
}
console.log(obj2+'test');
答案 0 :(得分:0)
import {Component} from "@angular/core";
import {AuthService} from "./AuthService";
interface Credentials {
username: string,
password: string
}
@Component({
selector: 'login',
template: `
<form #f="ngForm" (ngSubmit)="onLogin(f.value)" *ngIf="!auth.loggedIn()">
<input type="text" placeholder="username" ngControl="username">
<input type="password" placeholder="password" ngControl="password">
<button type="submit">Submit</button>
</form>
`
})
export class LoginComponent {
credentials: Credentials;
constructor(private auth: AuthService) {}
onLogin(credentials) {
console.log("username"+credentials.username,"password"+credentials.password);
this.auth.login(credentials);
}
}
答案 1 :(得分:0)
AJAX将来会返回结果(这就是为什么它是异步的)。由于JavaScript在单个线程中运行,因此无法立即返回值。
您需要了解jQuery的Promise API,$.post
已经支持。
稍微修改一下代码,以充分利用代码中的promises功能。
function ajax_call() {
return $.post("action.php", {action: 'view_style_code_action',style_val: v})
}
ajax_call()
.then(function(data) {
// Do the parsing here
var obj3 = $.parseJSON(data);
// Do rest of your work here.
...
});