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; } }); }/* 结果 无返回 */
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 }
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 })
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!