jQuery AJAX PHP数据返回


                    

我在Jquery中使用ajax函数通过json_encode函数从PHP脚本返回一些值。 返回的数据似乎充满了斜杠,引号和
。 我知道,反斜杠或magic_quotes(已打开)肯定有问题,但似乎无法获得干净的输出</ p>
     </ div>

展开原文

原文

I'm using the ajax function in Jquery to return some values from a PHP script with the json_encode function. The returned data seems to be full of slashes, quotes and . I understand that there must be something going wrong with stripslashes or magic_quotes (which is turned on) but can't seem to manage to get a clean output

1个回答


确保在从jQuery进行ajax调用时,告诉它期望json响应。 听起来您正在返回纯文本并尝试手动解析它。</ p>

  $。ajax({
   网址:“ myscript.php”,
   dataType:“ json”,
   成功:功能(数据){
     console.log(data); //此行仅适用于chrome(标准版)或FireFox(具有FireBug插件)
   }
});
</ code> </ pre>

该代码将在您的控制台中回显(如果您没有FireBug的chrome或FF,请获取其中之一:P)json编码的输出。 记住,当您从PHP输出时,您应该做的就是这样:</ p>

  header('Content-type:application / json');
回声json_encode($ myAssociativeArrayOfData);
出口; //确保没有其他东西输出任何东西
</ code> </ pre>

您不需要使用任何特殊的格式或斜杠。 只要确保json代码以正确的标头形式输出为json代码,jQuery的ajax函数就应该为您转换它。 结果将是成功函数中的数据变量,即您的json对象(php数组)。 因此,如果您在PHP中传入这样的数组:array('foo'=>'bar'),则在jquery的成功函数中,您可以输入:alert(data.foo); 并显示一个对话框,显示“ bar”。</ p>
     </ div>

展开原文

原文

Make sure on your ajax call from jQuery, you tell it to expect a json response. It sounds like you're returning plaintext and trying to parse it manually.

$.ajax({
  url: "myscript.php",
  dataType: "json",
  success: function(data){
    console.log( data ); //this line only works with chrome (stock) or FireFox (with FireBug plugin)
  }
});

That code will echo in your console (if you don't have chrome or FF with FireBug, go get one of them :P) the json encoded output. Remember when you output from PHP, all you should be doing is this:

header('Content-type: application/json');
echo json_encode( $myAssociativeArrayOfData );
exit; //make sure nothing else happens to output something

You don't need to use any special formatting or slashes. Just make sure the json code gets output as json code with the proper headers and jQuery's ajax function should convert it for you. The result will be the data variable in the success function being your json object (php array). So if you pass in an array like this: array('foo'=>'bar') in PHP, then in your success function in jquery, you could type: alert( data.foo ); and get a dialog box that says "bar".

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐