如何在ajax中发送POST数据?

新手上路,请多包涵

我需要编写一个脚本来接收和解析 POST 数组中的 JSON 数组。为了做到这一点,我首先尝试将任何旧的 JSON 数据发送到我的脚本,以便我可以使用一些东西。

我的接收脚本是用 PHP 编写的(但也可以用 Javascript 完成。)现在,我只是序列化 POST 数组并将其写入文本文件以确保有内容进入。它正在写的是一个空数组,尽管。

我正在尝试使用 ajax 请求发送数据。这就是我现在所拥有的:

 <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
        var jsondata = JSON.stringify({
            val1:"this",
            val2:"that"
        });

        $.ajax({
            url: "http://api.mydomain.com/test/index.php",
            method: "POST",
            data: {json: jsondata},
            contentType: "application/json",
            success: function(data){alert(JSON.stringify(data));},
            error: function(errMsg) {
                alert(JSON.stringify(errMsg));
            }
        });
    });
    </script>
</head>
<body>
</body>
</html>

我也尝试了很多变体,包括

  • 不对 jsondata 进行字符串化
  • 将数据更改为: data: jsondata
  • 在请求中使用 type: 而不是 method:
  • 在请求中包括 datatype: "json"

以及其他一些我什至不记得的变体。我错过了一些简单的东西吗?或者有更简单的方法来完成这个吗?

编辑:添加我的 index.php 文件

if (isset($_POST)){
    // This line is commented out because it breaks it.
    //$jspost = json_decode($_POST['json']);
    $jsser = serialize($_POST);
    echo "I'm here.";
    // Write to text file
    $myfile = "response.txt";
    $fh = fopen($myfile, 'w') or die("can't open file");
    $now = date("n/j/y g:i:s a");
    fwrite($fh, $now."\r\n");
    fwrite($fh, "I received a POST.\r\n");
    fwrite($fh, $jsser);
    fwrite($fh, "\r\n\n");
    fclose($fh);
}

原文由 user3353762 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 489
1 个回答

JS

发送一个 JSON 字符串

    $(document).ready(function () {
        var obj = {
            val1: "this",
            val2: "that"
        };
        obj.val3 = 'these';
        obj['val4'] = 'those';
        $.ajax({
            type: "POST",
            url: "service.php",
            data: {
                 json: JSON.stringify(obj)
            },
            success: function (response) {
                //service.php response
                console.log(response);
            }
        });
    });

服务.php

解码并处理接收到的对象

$json = filter_input(INPUT_POST, 'json');
$decoded_json = json_decode($json);
$val1 = $decoded_json->val1;

var_dump($decoded_json, $val1);

反之亦然,如果你想从 php 发送一个 JSON 并将其解码为 JS

PHP

 $responseArray = array();
$responseArray['key1'] = 'value1';
$responseArray['key2'] = 'value2';

echo json_encode($responseArray);

JS

 success: function (response) {
    var decodedJson = JSON.parse(response);
    console.log(decodedJson['key1']);
}

原文由 Cafaro Rosario 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题