通过 jquery 返回字符串的同步 ajax 调用
我正在对 ajax 进行 jQuery 同步调用——返回类型设置为“json”——但是返回数据以字符串形式返回。我做错了什么,或者是否可以将字符串转换为对象?
var ajax_response = $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, dataType:"json"});
var data = ajax_response.responseText;
ajax 调用正在工作,正如我可以在调试器中看到结果一样,只是返回的数据位于字符串中。
I am making a jQuery synchronous call to ajax -- with the return type set to "json" -- however the return data is coming back as a string. Is there something I'm doing wrong, or is there away to convert the string to an object?
var ajax_response = $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, dataType:"json"});
var data = ajax_response.responseText;
The ajax call is working, as I can see the results in the debugger, it is simply that the returned data is in a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
responseText 将始终是一个字符串。在 $.ajax() 中添加一个带有参数的“成功”回调函数,该函数将是 JSON 数据。
responseText will always be a string. within $.ajax() add a 'success' callback function with a parameter and that will be the JSON data.
这是因为 $.ajax() 将返回一个实际的 XMLHttpRequest ..其
responseText
没有 JSON 等概念。试试这个:
因为
ajaxResponse
是在父闭包中定义的在ajax()
调用中定义的函数,它可以设置为success
函数提供的 JSONdata
对象(即当 Ajax 请求成功完成时调用)。然后,父闭包返回ajaxResponse
,然后将其分配给外部data
变量。请注意,这种从
ajax()
立即返回修改后的ajaxResponse
的能力只有在请求是同步时才可能实现。如果是异步的,return ajaxResponse
很可能会返回一个空字符串。That is because $.ajax() will return an actual XMLHttpRequest .. whose
responseText
has no concept of JSON etc.Try this:
Since
ajaxResponse
is defined in the parent closure of the function defined in theajax()
call, it can be set to the JSONdata
object that is provided by thesuccess
function (which is called when the Ajax request successfully completes). Then,ajaxResponse
is returned by the parent closure, which is then assigned to the outsidedata
variable.Note that this ability to immediately return the modified
ajaxResponse
from theajax()
is only possible because the request is synchronous. If it were async,return ajaxResponse
would very likely return an empty string.这种方式应该可行,使用 eval 函数:
但正如之前所说,您应该使用 jQuery 成功回调,它的存在是为了让您的生活更轻松。
That way should work, using the eval function:
But as it has been said before, you should use jQuery success callback, which exists to make your life easier.