Home > Backend Development > PHP Problem > ajax cannot get php return value

ajax cannot get php return value

angryTom
Release: 2023-02-26 22:34:01
Original
4770 people have browsed it

ajax cannot get php return value

The solution to the problem that ajax cannot get the php return value:

1. First check whether ajax is It is asynchronous. Async cannot directly return the result.

/*常见错误示例  直接在 ajax 里面return 结果*/

 function demo(){
     $.ajax({
         url : 'test.do',
         type : "post",
         data : {},
         async : false,
         success : function(data) {             return 2;
         }
     });
 }/* 结果  无返回 */
Copy after login

2. Then ensure that ajax does not return data in the nested function. The function that calls ajax should return the data.

/**
 * (1)同步调用 (2)且在ajax对全局变量进行设值 (3)ajax函数外将变量return
 * 结果:返回 2。成功获取返回值
 * 成功原因:先执行result = 2;再往下执行return result;
 */
function demo1(){
    var result = 1;
    $.ajax({
        url : 'test.do',
        type : "post",
        data : {},
        async : false,
        success : function(data) {
            result = 2;
        }
    });
    return result;  //2
}
Copy after login

3. It can run normally. However, changing ajax to a synchronous request will cause blocking; ajax requires an asynchronous request.

/**
  * 添加async:true.即修改为异步
 * 结果以callback的形式回调
  */
 function demo1(params,callback){
    var result = 1;
     $.ajax({
        url : 'test.do',
         type : "post",
         data : {"params ":params },
         async : true,
         success : function(data) {
             result = 2;
             callback(result);
         }
     });
 }    

demo1("Value",function(rs){
   //do someting
})
Copy after login

Note: The php requested by ajax requires echo or print data, otherwise ajax will not be able to obtain the data.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of ajax cannot get php return value. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template