简体   繁体   English

如何使用jQuery.post将JSON数据发送到php脚本?

[英]How do I use jQuery.post to send JSON data to a php script?

This is in my javascript code. 这是在我的JavaScript代码中。 The variable dataStore is a valid JSON object and the JSON.stringify works fine - I tested with console.log() to be sure. 变量dataStore是有效的JSON对象,并且JSON.stringify可以正常工作-我确实使用console.log()进行了测试。

I'm new to jQuery and have not written a CGI application in awhile so I may be doing something incorrect here. 我是jQuery的新手,已经有一段时间没有编写CGI应用程序了,所以我在这里可能做错了什么。

jQuery.post("taskmanager.php", JSON.stringify(dataStore), function (returnData) { 
    alert(returnData); 
});

The taskmanager.php script resides in the same folder as my other files ( taskmanager.html, taskmanager.css, taskmanager.js ). taskmanager.php脚本与其他文件(taskmanager.html,taskmanager.css,taskmanager.js)位于同一文件夹中。 This folder resides on my Windows7 folder E:\\JamesLaderoute\\MySoftware\\WebApp\\TaskManager\\code 该文件夹位于我的Windows7文件夹E:\\ JamesLaderoute \\ MySoftware \\ WebApp \\ TaskManager \\ code

I'm not sure what to put into the taskmanager.php script. 我不确定要在taskmanager.php脚本中放什么。 I thought I could do something simple like: 我以为我可以做一些简单的事情,例如:

<?php

    $data = $_GET["data"];

    echo "done";

?>

What I don't understand is, how will the php script know that my JSON stringify information was called "data". 我不明白的是,PHP脚本如何知道我的JSON字符串化信息称为“数据”。

Also, I thought jQuery.post() takes the script name as the first argument, and then the data to be sent to the script followed by a callback function that gets called when the script returns data via echo calls. 另外,我以为jQuery.post()将脚本名称作为第一个参数,然后将要发送到脚本的数据发送给脚本,接着是一个回调函数,当脚本通过echo调用返回数据时将调用该回调函数。

The alert() does get called but it's displaying the php script rather than the string "done" alert()确实被调用,但是它显示的是php脚本,而不是字符串“ done”

I've searched the internet (a little bit) and found examples that use something called AJAX to send data to a script like php. 我搜索了一下互联网(找到了一点),并找到了一些示例,这些示例使用称为AJAX的东西将数据发送到php之类的脚本。

I learn best with a small example, is there a good example that points out what I'm missing? 我通过一个小例子学习得最好,有没有一个好的例子指出我所缺少的东西? How do I get this to work? 我该如何工作?

Eventually I plan on taking whatever the JSON data is and saving it to a file on the server. 最终,我计划采用任何JSON数据并将其保存到服务器上的文件中。 Do I need to run this all with a real server? 我是否需要在真实服务器上运行所有这些? Right now I'm not using one but I do have WAMP setup so I could use that if that is what is required. 现在我没有使用WAMP,但是我有WAMP设置,所以如果需要的话,我可以使用它。

Thank you to everyone who posted answers to my problem. 感谢所有发布我的问题答案的人。 I'm editing this post to show the actual code I ended up using to get my application working. 我正在编辑这篇文章,以显示最终用来使应用程序正常工作的实际代码。

JavaScript code: JavaScript代码:

alert(returnData); });
        $.ajax({
            url : "taskmanager.php" ,
            type : 'POST',
            data : JSON.stringify(dataStore),
            success : function(res) {
                    // Successfully sent data
                  console.log(res);
            },
            error: function(err) {
                // Unable to send data
                  console.log(err);
            }
        });

PHP code: PHP代码:

<?php

    $contents = file_get_contents('php://input');
    $data = json_decode( $contents );

    file_put_contents( "taskdata.json",  "data=".$contents );

    echo "<br>done</br>";

?>

Default Content-Type for jQuery ajax data is application/x-www-form-urlencoded which is very easy to work with in php using $_GET , $_REQUEST and $_POST and doesn't require stringifying as json jQuery ajax数据的默认Content-Typeapplication/x-www-form-urlencoded ,使用$_GET$_REQUEST$_POST在php中非常容易使用,并且不需要将字符串化为json

Pass an object directly to $.post (or any of the $.ajax methods) and jQuery will encode it internally 将对象直接传递到$.post (或任何$ .ajax方法),jQuery将在内部对其进行编码

var data ={foo:'bar'};
$.post('taskmanager.php', data, function(resp){
   console.log(resp);
})

php 的PHP

echo $_POST['foo'];

If you want to work with json only you need to set appropriate Content-Type 如果只想使用json,则需要设置适当的Content-Type

$.ajax({
   url:'...',
   method:'post',
   contentType:'application/json',
   dataType:'json',
   data: JSON.stringify(data)
}).done(function(resp){
   console.log(resp);
});

Then in php use: 然后在php中使用:

$data = json_decode(file_get_contents('php://input'));
$data['foo'] ='Some new value';
echo json_encode($data);

Using jQuery you can send data to your end point using the POST protocol. 使用jQuery,您可以使用POST协议将数据发送到端点。 Example below 下面的例子

$.ajax({
    url : 'taskmanager.php',
    type : 'POST',
    data : JSON.stringify(dataStore),
    success : function(res) {
        // Successfully sent data.
        console.log(res);
    },
    error: function(err) {
        // Unable to send data.
        console.log(err);
    })
});

You may also use the $.post method, its just a preference. 您也可以使用$ .post方法,它只是一个首选项。 $.ajax provides with some extra flexibility, in case you maybe want to update your protocol to GET instead of post or numerous other instances... $ .ajax提供了一些额外的灵活性,以防您可能想将协议更新为GET而不是post或其他许多实例...

More info on this here: http://forum.jquery.com/topic/what-should-i-use-post-vs-ajax 此处的更多信息: http : //forum.jquery.com/topic/what-should-i-use-post-vs-ajax

I usually use the following to POST JSON to php... 我通常使用以下内容将JSON发布到php ...

$.post("publishdata.php", {
    dataArray: arrayOfStuff,
    meetingTitle: meetingTitle,
    meetingDate: meetingDate
},
function(data, status, response) {

     console.log(response);


});

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

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