【问题标题】:How to send json to php via ajax?如何通过ajax将json发送到php?
【发布时间】:2015-04-22 07:17:23
【问题描述】:

我有一个收集用户信息的表单。我将这些信息编码为 JSON 并发送到 php 以通过 AJAX 发送到 mysql db。下面是我放在</body>前面的脚本。

现在的问题是,结果并没有像预期的那样得到警报。所以我相信ajax请求没有正确发出?有人可以帮忙吗?谢谢。

<script>
    $(document).ready(function() {
    $("#submit").click(function() {
        var param2 = <?php echo $param = json_encode($_POST); ?>;
        if (param2 && typeof param2 !== 'undefined')
        {
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: param2,
                cache: false,
                success: function(result) {
                    alert(result);
                }
            });
        }
    });
});
</script>

ajaxsubmit.php

<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>

【问题讨论】:

  • 这里的dataString是什么
  • 什么是dataString?您还可以检查开发工具中的网络选项卡以查看请求是否通过。
  • 您能否详细说明“结果未按预期发出警报”?
  • @NarendraSisodia,对不起,我现在改成param2,要在php中解码的数据。
  • @WaiHaLee,在我的 ajax 脚本中我写了 alert(result);我希望 php 文件的任何结果都会出现在警告框中。

标签: php mysql json


【解决方案1】:

您需要在 JSON 字符串周围添加引号。

var param2 = '<?php echo $param = json_encode($_POST); ?>';

【讨论】:

  • 谢谢!...现在至少它显示了警告框。但不回显 php 文件结果。出于测试原因,我只是回显“hi”;在php文件中无济于事
  • 您在 Chrome 开发工具中检查 XHR 请求时看到了什么?
  • 我是这样的:Uncaught SyntaxError: Unexpected token if
  • 向我们展示您的 PHP 文件的代码。是否以&lt;?php开头?
  • 我在上面显示的 php (ajaxsubmit.php)。现在我再试一次,它说 XHR 已加载。并在警报框中指出注意:未定义的变量名为 param2
【解决方案2】:

据我所知,你做错了。

假设您有一个 id 为“someForm”的表单

然后

$(document).ready(function () {
    $("#submit").click(function () {
        $.ajax({
            type: "POST",
            url: "ajaxsubmit.php",
            data: $('#someForm').serialize(),
            cache: false,
            success: function (result) {
                alert(result);
            }
        });
    }
    });
});

在 PHP 中,你会有这样的东西

$str = "first=myName&arr[]=foo+bar&arr[]=baz";

解码

parse_str($str, $output);
echo $output['first'];  // myName

对于 JSON 输出

echo json_encode($output);

【讨论】:

  • @Muztaza 我同意你的观点,我也猜到了,我做错了,但不确定是哪个。从你的回答我会得到我的ajax部分正确但是在json中编码和解码怎么样?我想将所有用户输入发送到 php 文件,这就是为什么使用 json_encode($_POST)。
  • 你不需要json。只要按照上面的代码,你就可以得到预期的结果了
  • @Muztaza 好的,但我不明白这部分 => $str = "first=myName&arr[]=foo+bar&arr[]=baz"; & 这部分=> parse_str($str, $output);回声 $output['first'];
  • $('#someForm').serialize(), 使用它会将您的表单输入转换为 first=myName&amp;arr[]=foo+bar&amp;arr[]=baz" 并将其传递给服务器,在 ajaxsubmit.php 中您需要使用 parse_str 解析结果
  • @Muztaza,序列化将像这样转换为 smtg:first=myName&arr[]=foo+bar&arr[]=baz,好的,我明白了..但是在 ajaxsubmit.php 我需要 parse_str($ str, $output);....请问我在哪里可以得到 $str 和 $output?
【解决方案3】:

如果您将 JSON 作为 ajax 响应返回,那么首先您必须在 AJAX 中定义响应的数据类型。

试试看。

 <script>
        $(document).ready(function(){  
$("#submit").click(function(){
      var param2 = <?php echo $param = json_encode($_POST); ?>
            if( param2  && typeof param2 !== 'undefined' )
                     {
                  $.ajax({
            type: "POST",
            url: "ajaxsubmit.php",
            data: dataString,
            cache: false,
            dataType: "json",
            success: function(result){
            alert(result);
            }
              });}
            });
});
    </script>

【讨论】:

  • 我试过你的方法......但它没有显示结果,因为我相信 ajaxsubmit.php 文件是错误的?哪个变量以及我如何使用它在 php 中解码请..from ajax 我在 javascript 中传递 param2
【解决方案4】:

真的很简单!

$(document).ready(function () {
    var jsonData = {
                    "data" : {"name" : "Randika",
                               "age" : 26,
                            "gender" : "male"
                     }
                  };
  
    $("#getButton").on('click',function(){
	    console.log("Retrieve JSON");
        $.ajax({
            url : "http://your/API/Endpoint/URL",
            type: "POST",
            datatype: 'json',
            data: jsonData,
            success: function(data) {
                console.log(data);  // any response returned from the server.
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">

如需进一步阅读和参考,请点击以下链接:

  1. Link 1 - jQuery 官方文档
  2. Link 2 - 各种类型的 POST 和 AJAX 使用。

在我的示例中,代码 sn -p PHP 服务器端应如下所示:

 <?php
    $data = $_POST["data"];
    echo json_encode($data);  // To print JSON Data in PHP, sent from client  side we need to **json_encode()** it.
    // When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it

    if($data != null) {
       $data = json_decode($data);
       $name = $data["name"];
       $age = $data["age"]; 
       $gender = $data["gender"];
       // here you can use the JSON Data sent from the client side, name, age and gender.
    }
 ?>

再次与您的问题更相关的代码 sn-p。

     // May be your following line is what doing the wrong thing
    var param2 = <?php echo $param = json_encode($_POST); ?>
  
    // so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
  
     console.log("param2 "+param2);
     <?php echo "// ".$param; ?>

【讨论】:

  • 感谢您显示代码 sn-p... 我认为我的代码现在只工作了一部分,我不明白的是 php 文件。现在我的 ajax 正在向 php 提交请求,但 php 无法解码,因为变量未定义,所以它在警报框中显示。
  • 嘿,我已经编辑了我的答案,请检查一下,看看答案是否正确。 :-) 干杯!
  • 您的变量名具有误导性。您根本没有将 JSON 发送到 PHP。为什么你有crossDomain:true,
  • @Randika,我认为它不涉及 JSON?我的 ajax 现在可以工作了,但我只需要知道如何解码 php 中的 json..使用哪个变量?
  • @Quentin 请解释为什么你认为我的变量名具有误导性?我刚刚举了一个例子。而且你不能假设我的 ajax 调用没有向 PHP 或 Java API 发送数据!它在服务器端实现不是吗?无论如何,到目前为止,我也添加了如何在 PHP 中解码 JSON!希望这会有所帮助!
【解决方案5】:

经过谷歌的一些研究,我找到了以 JSON 格式提示结果的答案!

感谢大家的时间和精力!

<script>
$("document").ready(function(){
  $(".form").submit(function(){
    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "response.php", //Relative or absolute path to response.php file
      data: data,
      success: function(data) {
        $(".the-return").html(
          "<br />JSON: " + data["json"]
        );

        alert("Form submitted successfully.\nReturned json: " + data["json"]);
      }
    });
    return false;
  });
});

</script>

response.php

<?php
if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
      case "test": test_function(); break;
    }
  }
}

//Function to check if the request is an AJAX request
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
  $return = $_POST;


  echo json_encode($return);

}
?>

这是参考链接:http://labs.jonsuh.com/jquery-ajax-php-json/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多