繁体   English   中英

从PHP中的jQuery结果解析JSON回复

[英]Parse a json reply from a jquery result in php

我有一个简单的搜索表单,该表单使用jquery向外部服务器查询结果

$("#formsearch").on("submit", function (event) {
        // everything looks good!
        event.preventDefault();
        submitFormSearch();
});
function submitFormSearch(){
    // Initiate Variables With Form Content
    var searchinput = $("#searchinput").val();
    $.ajax({
        type: "GET",
        url: "https://external-server/api/",
        headers: {"Authorization": "xxxxxxxxxxxxxx"},
        data: "action=Search&query="+searchinput,
                success:function(json){
                    console.log(json);
                    $.ajax({
                        type: "POST",
                        url:'search_func.php',
                        data: "func=parse&json="+json,
                        success:function(data) {
                            console.log(data);
                            $('#risultato_ricerca').html(data);                         
                            }
                    });
                }
    });
}

第一个GET ajax可以正常工作,并且我获取了正确的数据,但是在发布后尝试将此json数据发送到我的php脚本中时,我无法获取数据。 这是search_func.php中的代码

if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
    case 'parse':
            parse($_POST['json']);
            break;
        default:
            break;
    }
} 
function parse($json) {
    $obj = json_decode($json,true);
    var_dump($obj);
}

...显示NULL

我哪里错了?

编辑:已解决

改变:
data: "func=parse&json="+json, to: data: { func: 'parse', json: JSON.stringify(json) },

json代码已正确传递给search_func.php将php文件中的函数解析更改为:

function parse($json) {
    $data = json_decode(stripslashes($json),true); 
    print_r($data);
}

谢谢。

javascript json变量是否正确填充(即您的控制台向您显示了什么?)可能您必须在发布前将json变量编码为字符串。

即:代替data: "func=parse&json="+json,使用data: "func=parse&json="+JSON.stringify(json),

看到这个: http : //api.jquery.com/jquery.ajax/

正确的语法是: data: { func: 'parse', json: my_json_here }

如果这不起作用,可能是您必须将JSON编码为字符串(请参阅JSON.stringify() )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM