AJAX responseText undefined

感情迁移 提交于 2019-12-11 09:47:39

问题


Javascript code:

...............
...............
var cutid = $(th).attr("data-cutid");

var request = $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Services/Cut.asmx/CheckCuts",
    data: "{'cuts':" + JSON.stringify(ListCuts) + ",'idCut':'" + cutid + "'}",
    dataType: "json"
}).responseText;

alert(request); // undefined

Function from web service:

    [WebMethod]        
    public string CheckCuts(List<CutM> cuts, Guid idCut)
    {
        return UtilCut.CheckCuts(cuts, idCut).ToString();
    }

The responseText is undefined. Why?


I added async: false to ajax request. Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.

This code works:

function AjaxCheckCuts(ListCuts,cutid) 
{
    var request = $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Services/Cut.asmx/CheckCuts",
    async: false,
    data: "{'cuts':" + JSON.stringify(ListCuts) + ",'idCut':'" + cutid + "'}",
    dataType: "json"       
    }).responseText;

    var r = jQuery.parseJSON(request);
    r = r.d;
    return r;
}

回答1:


Is the web service working correctly? Is it returning a HTTP 200? Can you see the data that is being returned using F12 tools or Fiddler?

$.ajax() is returning a deferred. Define a done method for it to execute when the async call completes. There is no responseText property, that's why it is returning a undefined.

Try this:

var cutid = $(th).attr("data-cutid");

var request = $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Services/Cut.asmx/CheckCuts",
    data: "{'cuts':" + JSON.stringify(ListCuts) + ",'idCut':'" + cutid + "'}",
    dataType: "json"
});

request.done(function(result){
    alert(result);
});


来源:https://stackoverflow.com/questions/25620216/ajax-responsetext-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!