如何在ajax中发送POST数据?

时间:2016-01-19 16:31:01

标签: javascript 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);
}

3 个答案:

答案 0 :(得分:3)

<强> JS
发送JSON字符串

List<string> uniqueColors = autoBody.Select(auto => auto.SelectedCar.Color)
                                    .Distinct()
                                    .ToList()

<强> service.php
解码并处理收到的对象

    $(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并将其解码为JS

<强> PHP

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

var_dump($decoded_json, $val1);

<强> JS

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

echo json_encode($responseArray);

答案 1 :(得分:0)

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

<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 :(得分:-1)

试试这个

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
        }
    });
相关问题