什么返回的jQuery的ajax数据参数在回调函数? [英] What to return for jQuery's ajax data param in callback function?

查看:367
本文介绍了什么返回的jQuery的ajax数据参数在回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery的ajax函数来调用url asynchron,如下所示:

  jQuery.ajax({
url :url,
type:GET,
data:{key:value},
success:function(data){
console.log(data);
}
}



在服务器端我不知道返回什么

我已经尝试过<$ c $ $ c> return 0 return 1 return array('status'=> 1) return true



背景:我想知道是否在服务器端抛出了异常



编辑:服务器端语言是PHP

解决方案

假设您使用PHP,您只需回显一个字符串返回值。

  echo true; 
exit;

  echofalse; 
exit;

那么你可以用jQuery解析:

  if($ .trim(data)==true){
console.log(success!)
}
else {
console.log(data);
}

你也可以回显0或1,但是记住它仍然是一个字符串,不是一个数字,当它得到jQuery。对于更复杂的数据,例如数组,可以对其进行json_encode。

  echo json_encode($ myarray); 
exit;

并将 dataType 设为json在jQuery的 $。ajax 方法中。


I use jQuery's ajax function to call a url asynchron like this:

jQuery.ajax({
    url: url,
    type: "GET",
    data: {key : value},
    success: function(data) {
        console.log(data);
    }
}

On the server side I don't know what to return to get something meaningful inside the variable data. The console's log is just empty string.

I already tried return 0, return 1, return array('status' => 1), return true

Background: I want to know if any exceptions have been thrown on the server side to pass something like false or true if it was successful without exceptions.

EDIT: Server side language is PHP

解决方案

Assuming you are using PHP, you would just echo a string return value.

echo "true";
exit;

or

echo "false";
exit;

then you can parse that with jQuery:

if ( $.trim(data) == "true" ) {
    console.log("success!")
}
else {
    console.log(data);
}

You could also echo 0 or 1, but keep in mind it's still a string, not a number when it gets to jQuery. For more complex data, such as an array, you can json_encode it.

echo json_encode( $myarray );
exit;

and set your dataType to "json" in jQuery's $.ajax method.

这篇关于什么返回的jQuery的ajax数据参数在回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆