使用AJAX将数据发送到PHP

时间:2015-10-21 04:52:45

标签: javascript php jquery html ajax

我在发布此问题之前搜索了我的问题,但未能找到解决方案。 我需要将一个json字符串发送到php文件但无法这样做,有人可以帮我解决下面的问题:我是php和jquery的新手并且正在努力,需要你的合作。

我有一个捕获文本文件数据的函数:

function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
    var node = node_list[i];
    if (node.getAttribute('type') == 'text') {
        fieldName[c] = node.name;
        fieldText[c] = node.value;
        ID[c] = node.id;
        c++;
    }
}
var postData = {
    fieldName: fieldName,
    fieldText: fieldText,
    ID: ID
};
 var dataString = JSON.stringify(postData);


console.log(JSON.stringify(postData));
$.ajax({
        type: "POST",
        dataType: "json",
        url: "update.php",
        data: {myData:postData}
        })

//return JSON.stringify(postData);
}

我的update.php是这样的:

<?php
$json = $_POST['json'];
$result = json_decode($json);

echo $result;
echo $_POST['myData']);?>

加载时:我收到以下错误:

  

无法加载资源:服务器响应状态为500(内部服务器错误)

此外,我不确定是否将数据发送到php。 专家们可以证实。

5 个答案:

答案 0 :(得分:3)

500(内部服务器错误)意味着服务器端出现了问题。因此,请查看apache错误日志以获取更多详细信息

您可以在此处找到apache登录/var/log/apache2/

答案 1 :(得分:2)

在客户端(javascript代码):

data: JSON.stringify(postData)

在服务器端(PHP代码):

json_decode($_POST["data"])

答案 2 :(得分:1)

你用return语句评论了函数的结束括号。 改变这个:

//return JSON.stringify(postData);}

为:

//return JSON.stringify(postData);
}

另外:

data: JSON.stringify(postData),

IN update.php

$json = $_POST['myData'];
$result = json_decode($myData);

var_dump($result);

答案 3 :(得分:0)

来自@Tushar的评论帮助我解决了这个问题

contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: {json: JSON.stringify(postData)

答案 4 :(得分:0)

向php页面发送Ajax请求以获取数据

$.ajax({ method: "POST", // it may be Get url: "some.php", //page where you sent request data: { name: "John", location: "Boston" } //attibutes you want to take on that page }) .done(function( msg ) { // sucessfull reponse alert( "Data Saved: " + msg ); });