AJAX returns null?

2020-02-14 07:15发布

I am trying to use ajax to get information from my server. the page xxx.php is a page with only 123 written on it. However, when I want to return the content of that page, it returns null.

function myFunct(){
    $.ajax({
        url: 'xxx.php',
        success: function(data) {
            return data;
        }
    });
}

var data = myFunct(); //nothing.

标签: jquery ajax
5条回答
贪生不怕死
2楼-- · 2020-02-14 07:44

Try to use a ajax error handling, for check your response

function myFunct(){
$.ajax({
    url: 'xxx.php',
    success: function(data) {
        alert(data);
    },
    error:  function(jqXHR, textStatus){
       alert("Status: "+ jqXHR.status);
       alert("textStatus: " + textStatus);
    }

});

}

查看更多
\"骚年 ilove
3楼-- · 2020-02-14 07:47

AJAX is asynchronous.

You only get a response some time after the rest of your code finishes running.

Instead, you need to return the value using a callback, just like $.ajax does:

function myFunct(callback){
    $.ajax({
        url: 'xxx.php',
        success: function(data) {
            // Do something to the data...
            callback(data);
        }
    });
}

myFunct(function(result) {
    ...
});
查看更多
萌系小妹纸
4楼-- · 2020-02-14 07:54
var globalVal;

    function myFunct(){
        $.ajax({
            url: 'xxx.php',
            success: function(data) {
                alert(data); // you can see you data
                globalVal= data;
            }
        });
    }

// it is response to server, and response executed a bit latter that you assign value

myFunct(); //nothing.
alert(globalVal) 
查看更多
Deceive 欺骗
5楼-- · 2020-02-14 08:01

You can use in synchronized mode (despite being recommended with async callback to avoid "freezing" of the code).

Using synchronized:

function myFunct(callback){
   return $.ajax({
        url: 'xxx.php',
        async: false
    }).responseText;
}
查看更多
家丑人穷心不美
6楼-- · 2020-02-14 08:09

Please note that ajax is 'asynchronous'. So, the response to your server call may not received by the time myFunct() completes execution. You may put the logic of process the data from your server call in the 'success' of ajax.

function myFunct(){
    $.ajax({
        url: 'xxx.php',
        success: function(data) {
           // processMyData(data);
        }
    });
}
查看更多
登录 后发表回答