繁体   English   中英

处理获得ajax json请求的php

[英]Handle php which get ajax json request

假设我运行了这个ajax-

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

我想在它的json的内容- index.php ,并alerttest值(平均得到- 123 ),

我试过了-

index.php-

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

但是没有任何警报。

如何正确处理?

更新:

在@JayBlanchard评论之后,

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

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

您需要在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;
?>

您只需在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']));
?>

您必须定义一个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手册以安全地进行操作。

暂无
暂无

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

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