我有这样的代码:如何从后返回的数据变量的jQuery
function nameToCode(nameGroup) {
$.post("execute.php", { something: sendSomething }, function(data) {
return data;
});
}
variable = nameToCode("some text");
但只有我得到的变量就是不确定的,任何想法?谢谢。
我有这样的代码:如何从后返回的数据变量的jQuery
function nameToCode(nameGroup) {
$.post("execute.php", { something: sendSomething }, function(data) {
return data;
});
}
variable = nameToCode("some text");
但只有我得到的变量就是不确定的,任何想法?谢谢。
结果不会立即可用,所以你必须要有点不同构造代码:
function nameToCode(nameGroup, callback) {
$.post("execute.php", { something: sendSomething }, function(data) {
callback(data);
});
}
nameToCode("some text", function(variable)
{
/* use variable here */
});
你不能得到回调是这样的。有一个异步问题。 你可以用.ajax代替.post;
function nameToCode(nameGroup, callback) {
$.ajax({
url: 'execute.php',
type: 'POST',
aysnc:false,
data: 'something=sendSomething',
success: function(data) {
return data;
}
});
这会工作。
你的意思是,它不工作,或者你不喜欢解决方案?
这是关于JavaScript的工作过程。 js不会等待任何同步操作。你可以在成功功能块中完成你的工作,或者你必须使用async:false参数。我建议你做任何你想成功的功能块。如果您使用aysnc:false,它会在短时间内阻止您的浏览器。
$.post
的第四个参数是dataType。 您可以将其设置为JSON,以便将返回数据解析为JavaScript对象或数组。
$.post(
"execute.php",
{ something: sendSomething },
function(data){ return data; },
'json');
在你execute.php文件,你可以这样做
<?php
$return_data=array('nameToCode'=>'some text');
header('Content-Type: application/json');
echo json_encode($return_data);
exit();