开发者

synchronous ajax call via jquery returning string

开发者 https://www.devze.com 2022-12-13 12:28 出处:网络
I am making a jQuery syn开发者_开发问答chronous 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 the

I am making a jQuery syn开发者_开发问答chronous 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.


responseText will always be a string. within $.ajax() add a 'success' callback function with a parameter and that will be the JSON data.

$.ajax({
    -- other stuff --
  , success: function(data)
    {
        // do something with data
    }
});


That is because $.ajax() will return an actual XMLHttpRequest .. whose responseText has no concept of JSON etc.

Try this:

var data = (function () {
    var ajaxResponse = '';
    $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, success: function (data) {
        ajaxResponse = data;
    }, dataType:"json"}); 
    return ajaxResponse;
}());

Since ajaxResponse is defined in the parent closure of the function defined in the ajax() call, it can be set to the JSON data object that is provided by the success function (which is called when the Ajax request successfully completes). Then, ajaxResponse is returned by the parent closure, which is then assigned to the outside data variable.

Note that this ability to immediately return the modified ajaxResponse from the ajax() is only possible because the request is synchronous. If it were async, return ajaxResponse would very likely return an empty string.


That way should work, using the eval function:

var ajax_response = $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, dataType:"json"});
ajax_response.onreadystatechange = xHandler;

function xHandler() {
  if (ajax_response.readyState == 4) {
    var data = eval('(' + ajax_response.responseText + ')');
  }
}

But as it has been said before, you should use jQuery success callback, which exists to make your life easier.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号