试图将AJAX结果变量返回给JavaScript
注意下面的$.ajax
调用是同步的 (async: false
)。
Ajax调用
function getState(callback) {
$.ajax({
url: 'getSearchState.php',
data: { "state": callback },
type: 'GET',
async: false,
success: function(result){
alert(result);
},
error: function(result) {
alert(result);
}
});
}
Ajax PHP <?php
// Database Setup and Query
while ($row = $xxxxx->fetch(PDO::FETCH_ASSOC)) {
$StateVal = $row['State'];
}
return $StateVal;
?>
Javascript调用函数
var URL = District.trim();
var StateURL = getState(URL);
它从函数中获取URL变量,但不返回任何东西。
任何帮助将是伟大的!
这段代码在客户端和服务器端都有问题。
客户端:
你的getState
永远不会返回任何东西,所以你看不到StateURL
除了undefined
以外的任何东西也就不足为奇了。
不要使用同步ajax。这会导致糟糕的用户体验。但如果你真的,真的想继续使用它,你可以这样做:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
注意,我将参数的名称更改为state
,因为它不是回调。
但是,不要使用同步ajax。应该使用回调或承诺。
Promise: $.ajax
已经返回一个Promise,所以直接返回它:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
注意,我将参数的名称更改为state
,因为它不是回调。
但是,不要使用同步ajax。应该使用回调或承诺。
承诺:
function getState(state) {
return $.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET'
});
}
用法:
getState(URL)
.done(function(StateURL) {
// Use it
})
.fail(function() {
// Failed
});
回调:function getState(state, callback) {
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
success: function(data) {
// Call the callbback with the result
callback(data);
},
error: function() {
// Call the callback with an error
callback(/*...whatever you want to use tosignal an error */);
}
});
}
用法:
getState(URL, function(StateURL) {
// Use it, check for error
});
服务器端:正如RiggsFolly指出的那样,您的从PHP代码返回字符串。但这不会输出它。要在客户端使用它,您需要输出它(例如,echo
和类似的)。为了使它更容易被JavaScript使用,你可能想要json_encode
,以确保它是JavaScript可以理解的格式:
echo json_encode($stateVal);
然后在success
(或done
)函数中,使用JSON.parse
:
result = JSON.parse(data);
这是jQuery,在这种情况下,您可以指定上下文并在成功函数中设置该上下文上的变量....一个有点粗糙的解决方案,但它会起作用。还可以看看ES6中的箭头函数和承诺,它可以帮助你很多,并为你提供整个问题的新视角。
还有一件重要的事!!默认情况下,Ajax是异步的,所以当数据准备好时,你需要通知你的StateURL(这里再次承诺在你的服务中)