【问题标题】:How to send POST data in ajax?如何在ajax中发送POST数据?
【发布时间】:2016-04-25 05:37:54
【问题描述】:

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

我的接收脚本使用 PHP(但也可以使用 Javascript不过,空数组。

我正在尝试使用 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);
}

【问题讨论】:

  • JSON.stringify(data) 在您的成功回调中输出什么?
  • 我们可以看到你的 index.php 文件的内容吗?一个好的策略是在 php 脚本中执行 vardumps 和 die() 以确保不是服务器端错误。如果没有,console.log(JSON.stringify(data)) 来检查响应。
  • 成功回调中 JSON.stringify(data) 的输出是“我在这里。”,这是从 index.php 文件中回显的。
  • 我想通了!这是我的 contentType。当我将其设置为“application/x-www-form-urlencoded; charset=UTF-8”而不是“application/json”时,index.php 上的 var_dump 会显示通过的 jsondata 的值。

标签: javascript ajax post


【解决方案1】:

这对我有用...我没有使用表单,而是使用从元素收集的数据变量。之前的方法都试过了,没有结果。

<script>
    $(document).ready(function() {  
    var jsondata = new FormData();
    jsondata.append("val1", "this");
    jsondata.append("val2", "that");

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

【讨论】:

    【解决方案2】:

    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);
                }
            });
        });
    

    service.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']);
    }
    

    【讨论】:

    • 如果可以的话,我会给这个投票(没有足够的声望点),因为它有很多有用的信息,最终让我发现 contentType 是问题所在。
    【解决方案3】:

    试试这个

    var jsondata = {
            "val1":"this",
            "val2":"that"
        };  
    
        $.ajax({
            url: "http://api.mydomain.com/test/index.php",
            method: "POST",        
            data: jsondata,
            contentType: "json",
            success: function(data){
               //your success function
            },
            error: function(errMsg) {
                //your error function
            }
        });
    

    【讨论】:

    • 我刚刚尝试过,但是当我序列化 POST 并将其写入 response.txt 时仍然看到一个空数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2011-05-22
    • 2023-03-10
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多