【问题标题】:jquery post json data to PHP filejquery 将 json 数据发布到 PHP 文件
【发布时间】:2013-07-11 11:27:42
【问题描述】:

我有一个点击事件,我在其中编写了一个 json 数据,然后我想 将其发布到 PHP 文件中进行处理。但是出了点问题。 我的 PHP 文件现在被简化如下:

<?php
header('Content-Type: application/json');
 var_dump($_POST);
?>

POST-ing 的代码如下所示:

// myarray is: var myarray = new Array(); 
// and it gets populated above this code

var strObj = JSON.stringify(myarray);
alert(strObj); // so far I get the alert containing valid JSON text
$.ajax ({
  type:"POST",
  url:"proces.php",
  contentType: "application/json",
  dataType: "json",
  async: false,
  data: strObj,
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});

所以当我单击按钮时,我收到包含 JSON 字符串的警报(看起来不错),然后我收到警报说“错误”,当我检查控制台以获取 proces.php 的响应时,我看到的只是:

array(0) {
}

我做错了什么?我该怎么做才能改正?

【问题讨论】:

  • 我认为你需要将 header 更改为: header('Content-type: application/json'); (在 proces.php 的第 1 行)(并返回有效的 JSON 响应)
  • 我将标题添加到我的 php 文件中仍然没有什么新内容。反应是一样的。 (我更新了问题正文中的php)
  • 回显 json_encode($_POST);
  • console.log(this, arguments); 添加到错误回调并在控制台中检查您得到的确切错误;您在success 参数名称中也有错字。
  • @Tommi 我解决了成功参数问题。不是真正的问题。我在这里手动输入了代码(不是复制/粘贴),所以这只是一个错字。

标签: json jquery post


【解决方案1】:

这对我有用:

$.ajax ({
  type:"POST",
  url:"proces.php",
  dataType: "json",
  async: false,
  data: {tmp: strObj},
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});

【讨论】:

  • 我不知道怎么做,因为它对我不起作用。我的有效代码发布在此下方。我让它以某种方式工作:)
【解决方案2】:

我自己得到了答案。似乎可以解决问题:

$.post("proces.php", {json: JSON.stringify(myarray)}, function(data){alert(data);});

我的意思是,我没有收到警报(数据); (可能是因为我没有从 php 文件返回 JSON)但是在 PHP 中我现在可以看到 json 数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多