将AJAX PHP对象转换为字符串并回显结果

Convert AJAX PHP object to string and echo results

本文关键字:串并 字符串 结果 字符 AJAX PHP 对象 转换      更新时间:2023-09-26

我有以下php对象(??这是新手)。它正在通过AJAX从我的页面发送,并作为JSON发送。我正在解码它并试图回应结果,但我得到的都是NULL。在Firebug中,POST寡妇中的所有内容都显示得很好,但RESPONSE中没有任何内容(我认为这是我应该看的地方?)

header('Content-type: application/json');
$res = json_decode($_POST['apiresponse'], true);
echo $res;
  • JSON对象被传递到上面的PHP文件(传递前也被字符串化)
  • JSON被解码并保存为$res变量
  • Firebug POST窗口一切正常

我如何将其转换为PHP变量(字符串),我可以返回到我的原始PHP页面,以及

我如何发送/调用变量返回?* *

谢谢!

情况并非如此:(跳过!)如何将变量从javascript传递到php?我在这里只是猜测,但听起来很像你有

之类的东西

$.ajax( "/my-api-thing.php", { data: { "apiresponse": "some_value", "more":"things" } }).success(...);

如果是这种情况,那么你只期望json作为php脚本的结果,但是你实际上不是发送一个json对象作为请求,而是正常的http参数。

你可以在php中这样写:

$someVariable = $_POST["apiresponse"]

(顺便说一句:这将是"正常"的方式,发送json到服务器并不是那么常见)


更新猜

我已经验证了你用这个文件发布的json:

<form type="textarea" method="post">
<textarea name="apiresult" style="width: 400px;height:200px;">
    {"id":"-------","name":"Aaron ----------","first_name":"Aaron","last_name":"----","link":"http://www.facebook.com/-------","username":"-----","birthday":"05/06/1949","location":{"id":"-----","name":"Los Angeles, California"},"gender":"male","email":"------","timezone":-8,"locale":"en_US","verified":true,"updated_time":"2011-10-22T18:40:02+0000"}
</textarea>
<br>
<input type="submit">
</form>
<br>

<?php
if( isset( $_POST["apiresult"] ) ){
    echo "<pre>"; 
    echo $apiresult; 
    echo "'n----'n"; 
    print_r( json_decode( $_POST["apiresult"] ) ); 
    echo "</pre>"; 
}
?>

所以json_decode似乎根本不是问题。

其他一些猜测:

  1. 你有一个很旧的php版本,魔法引号是启用的(运行phpinfo检查!)
  2. 你正在使用一个php框架,它对post变量做一些预处理

要查明问题,您是否可以在json_decode之前运行echo $_POST["apiresponse"];以查看输出是否与输出不同?

来自PHP文档:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
"NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit."

检查的深度"$ _POST [' apiresponse ']"。