处理获取ajax json请求的php

时间:2014-06-11 14:21:02

标签: javascript php jquery ajax json

假设我运行此ajax -

$.ajax({
    url: "index.php",
    type: 'POST',
    data :{test : 123}, //updated due to the approved answer
    dataType: 'json'
});

我希望将其json内容添加到 - index.phpalerttest值(表示get - 123),

我试过了 -

的index.php -

<?php
    $json = $_POST["test"];
    echo '<script>';
    echo 'alert('+$json+');';
    echo '</script>';
?>

但没有任何警报。

如何正确处理?

更新

关注@JayBlanchard评论,

$json = $_POST["test"]真的得到test值吗?

alert对我来说并不重要,我只是想确保它是否在PHP方面正确解析,意味着让123回到客户端

3 个答案:

答案 0 :(得分:1)

您需要在JavaScript回调中处理来自php的结果。所以你可以这样做:

$.ajax({
    url: "index.php",
    type: 'POST',
    data :{text : 123},
    dataType: 'json',
    complete: function(data){
        console.log(data.responseText) //(not sure why responseText is necessary)
    }
});

你的php会是这样的:

<?php
$json = $_POST["text"];
echo $json;
?>

答案 1 :(得分:0)

您只需在success回调中执行此操作:

$.ajax({
    url: 'index.php',
    type: 'post',
    data: {text : 123},
    dataType: 'json',
    success: function(data) {
       alert(data.test);
    }
});

您的index.php

<?php
    echo json_encode(array('test' => $_POST['test']));
?>

答案 2 :(得分:0)

你必须定义一个javascript函数来处理响应:

var handle_response = function(data_from_server, StatusText, jqxhr) {
    // check http://api.jquery.com/jquery.ajax/ for StatusText and jqxhr meaning.
    alert(data_from_server);
}

然后你打电话给你的ajax

$.ajax({
    url: "index.php",
    type: 'POST',
    data :{text : 123},
    dataType: 'json',
    success: handle_response
});

你的php会像

<?php
    $json = json_decode($_POST["text"]);  // not sure about dataType: 'json'

    echo "this is coming from php on server ";
?>

如果你想执行从服务器创建的一些脚本检查jquery手册如何安全地执行它。