【问题标题】:AJAX call sending JSON dataAJAX 调用发送 JSON 数据
【发布时间】:2023-03-10 06:20:01
【问题描述】:

我正在开发一个使用 AJAX 自动刷新的聊天系统。首先我使用的是 jQuery $.post 函数,但是因为我想从我的 PHP 脚本返回 JSON 数据,所以我想使用 $.ajax 函数。我的脚本使用 $.post 函数运行良好,但我无法返回 JSON。这是相关代码: Javascript:

$.ajax({
    url: "pages/loadmessage.php",
    type: "POST",
    data: {"c": getUrlParameter("c"), "t": messagetime},
    dataType: "json",
    success: function(pData){
        console.log(pData);
    },
    error: function(xhr, status, error) {
        alert(error + status);
    }
});

PHP 代码:

<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
    $chat = new Chat($user->data()->ID, Input::get("c"));
    $messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
    if ($messages) {
        $result = array(
            'topic' => $chat->getTopic(),
            'messages' => array()
        );
        foreach($messages as $m) {
            array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
        }
        echo json_encode("string!!!");
    }
} else {
    echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>

我已经尝试将 AJAX 调用的 contentType 设置为“application/json”并使用 JSON.stringify 将数据转换为 JSON,但是没有输入数据到达 PHP 脚本。如果仅将一个参数(数据:{“c”:getUrlParameter(“c”)})发送到 PHP 脚本,则该代码有效... 我已经搜索过 StackOverflow,但我找不到解决方案...

谢谢

【问题讨论】:

  • $.post的最后一个参数你检查了吗?
  • 控制台中的任何错误消息
  • $.post 可以返回 JSON,您只需使用正确的语法:$.post( "pages/loadmessage.php", {"c": getUrlParameter("c"), "t": messagetime}, function( pData ) {/*do stuff*/}, "json");
  • $.post 只是 .ajax 的包装器。 json 也能正常工作
  • 您说过“使用 JSON.stringify,但没有输入数据到达 PHP 脚本”,如果是这种情况,您应该使用它来捕获服务器端的 json 字符串。 $rawData = file_get_contents("php://input"); // 如果无效则返回 null json return json_decode($rawData);

标签: javascript php jquery json ajax


【解决方案1】:

JSON 示例:

索引.html

<script type="text/javascript">

    $.ajax({
        url: "out.php",
        type: "POST",
        data: {"param1": "test 1", "param2": "test2"},
        dataType: "json",
        success: function(data){
            alert("param1:"+data.param1+" | param2:"+data.param2);
        },
        error: function(xhr, status, error) {
            alert(error + status);
        }
    });
</script>

out.php

<?php

    if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
    if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}

    $out = array("param1"=>$param1,"param2"=>$param2);

    echo(json_encode($out));
?>

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 2014-01-17
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2015-08-21
    相关资源
    最近更新 更多