函数返回Ajax响应-值未定义? jQuery Ajax [英] Function returns Ajax response - Value is undefined? jQuery Ajax
问题描述
当我警告jsonServerResponse函数返回的值时,尽管从process.php页面返回了JSON,但它的值是不确定的.
When I alert the returned value from the jsonServerResponse function, its value is undefined - despite JSON being returned from the process.php page.
function jsonServerResponse(operation, JSOoptionalData) {
JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
var jqxhr = $.ajax({
type: "POST",
url: "process.php",
data: "apicommand=" + JSOoptionalData,
success: function (json) {
return jQuery.parseJSON(json);
}
});
}
alert("Response as JS Object: "+jsonServerResponse("operation"));
我知道问题是异步请求完成之前发出的警报功能,但是我不确定如何解决此问题.任何建议都非常感谢:)
I know that the problem is that the alert function made before the asynchronous request is complete, but I am unsure how to fix this problem. Any advice is really appreciated :)
推荐答案
好吧,我是从另一篇文章中弄清楚的.结果可以在成功回调中处理,也可以添加本身是回调函数的参数并将ajax请求的结果应用于回调.
Ok, I figured it out from a different post. The result can either be handled within the success callback, or you can add an argument that is itself a callback function and apply the result of the ajax request to the callback.
function jsonServerResponse(operation, callback, JSOoptionalData) {
JSOoptionalData = (typeof JSOoptionalData == "undefined") ? 'defaultValue' : JSOoptionalData
jqxhr = $.ajax({
type: "POST",
contentType: "application/json",
url: "process.php",
data: "apicommand=" + operation + "&optionaldata" + JSON.stringify(JSOoptionalData),
dataType: "json",
success: function (json) {
if(typeof callback === 'function') callback.apply(this, [json]);
}
});
}
jsonServerResponse("get_something_from_server", function(returnedJSO){
console.log(returnedJSO.Result.Some_data);
}, "optional_data");
还有gdoron,您所询问的那一行使第三个参数成为可选参数.我听说这是一个好习惯,如果您要将一些数据传递到服务器上(但您不知道有多少变量)以添加可选参数并仅传递js对象,则将其转换为JSON字符串,然后将其解码为服务器-一侧.
And gdoron, the line you have asked about makes the third argument optional. I hear it's good practice, if you are going to pass some data onto the server (but you dont know how many variables) to add an optional argument and just pass a js object, convert this to a JSON string, and decode it server-side.
和平! :)
这篇关于函数返回Ajax响应-值未定义? jQuery Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!