如何通过 jQuery Ajax 发布数据在 PHP 中编码 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19381111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:23:07  来源:igfitidea点击:

How do I encode JSON in PHP via jQuery Ajax post data?

javascriptphpjqueryajaxjson

提问by SPG

I have an HTML form and send data to php file when hitting submit button.

我有一个 HTML 表单,并在点击提交按钮时将数据发送到 php 文件。

$.ajax({
    url: "text.php",
    type: "POST",
    data: {
        amount: amount,
        firstName: firstName,
        lastName: lastName,
        email: email
    },
    dataType: "JSON",
    success: function (data) {
        console.log("ok");
        $("#result").text(data);
    }
});

In PHP:

在 PHP 中:

<?php
    $amount      = $_POST["amount"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($amount)){
        $data = array(
            "amount"     => $amount,
            "firstName"  => $firstName,
            "lastName"   => $lastName,
            "email"      => $email
        );
        echo json_encode($data);
    }
?>

The result is [object object]. I want a type like:

结果是[对象对象]。我想要一个类型:

{"Amount":"12.34", "FirstName":"Any", "LastName":"Tester", "Email":"[email protected]"}

What have I done wrong?

我做错了什么?

回答by Jenson M John

Code example with JSON.stringify:

带有 JSON.stringify 的代码示例:

<html>
    <head>
       <title>jQuery Test</title>
       <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {
               $("#submit").click(function(){
                   $.ajax({
                       url: "text.php",
                       type: "POST",
                       data: {
                           amount: $("#amount").val(),
                           firstName: $("#firstName").val(),
                           lastName: $("#lastName").val(),
                           email: $("#email").val()
                       },
                       dataType: "JSON",
                       success: function (jsonStr) {
                           $("#result").text(JSON.stringify(jsonStr));
                       }
                   });
               });
           });
       </script>
    </head>

    <body>
        <div id="result"></div>
        <form name="contact" id="contact" method="post">
            Amount: <input type="text" name="amount" id="amount"/><br/>
            firstName: <input type="text" name="firstName" id="firstName"/><br/>
            lastName: <input type="text" name="lastName" id="lastName"/><br/>
            email: <input type="text" name="email" id="email"/><br/>
            <input type="button" value="Get It!" name="submit" id="submit"/>
        </form>
    </body>
</html>

text.php

文本文件

<?php
    $amount      = $_POST["amount"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($amount)){
        $data = array(
            "amount"     => $amount,
            "firstName"  => $firstName,
            "lastName"   => $lastName,
            "email"      => $email
        );
        echo json_encode($data);
    }
?>

回答by James P.

Your object is most likely being passed properly. It's the way you're capturing the result that returns [object object]as @Spudley explained. The console doesn't know how to display the construct but you can display specific attributes using the object.attributesyntax. Use console.log()on the JS side or the code below for a prettified output.

您的对象很可能被正确传递。这是您捕获结果的方式,[object object]正如@Spudley 所解释的那样。控制台不知道如何显示构造,但您可以使用object.attribute语法显示特定属性。使用console.log()的JS方或下方的美化输出的代码。

// Indent with tabs
// Data is the parameter sent to the success function in the ajax handler
JSON.stringify( data , null, '\t');

From How can I pretty-print JSON in (unix) shell script?

如何在 (unix) shell 脚本中漂亮地打印 JSON?

Also Temporarily remove dataTypeon the ajax handler if you sense there's a bug somewhere. Getting the ouput to show on a GET request should do. Change this back to POST for any operation that modifies something like a database delete or alter.

dataType如果您感觉到某处存在错误,请暂时删除ajax 处理程序。让输出显示在 GET 请求上应该可以。对于修改数据库删除或更改等内容的任何操作,将此更改回 POST。

Lastly, modify the header as shown in @GroovyCarrot's answer. If you're using Chrome the extra whitespace seems to be a bug: Tab and pre wrapped around JSON output in Chrome

最后,修改标题,如@GroovyCarrot 的回答所示。如果您使用 Chrome,额外的空格似乎是一个错误:Tab 和 pre 包裹在 Chrome 中的 JSON 输出

回答by GroovyCarrot

Try adding

尝试添加

header('Content-type: application/json');

At the top of your PHP script and see what you get back

在你的 PHP 脚本的顶部,看看你得到了什么

Hope that helps!

希望有帮助!

Edit: Forgot to mention you should access your values like so: data.amount

编辑:忘了提到你应该像这样访问你的价值观: data.amount

回答by Harry Bomrah

You cannot directly insert a JSON object to a dom. JSON object toString()method will always give u [object object], that is why you are getting this. You ve to parse the data by using JSON.stringify(data)or you have to run $.each(data,function(val){ $("#result").append(val) }).

您不能直接将 JSON 对象插入 dom。JSON 对象toString()方法总是会给你 [object object],这就是你得到这个的原因。您必须通过使用来解析数据, JSON.stringify(data)或者您必须运行$.each(data,function(val){ $("#result").append(val) }).

回答by baldrs

You're converting resulting object to string instead of displaying it.

您将结果对象转换为字符串而不是显示它。

Instead of result, if you want print object inside some wrapper, you can do something like this:

而不是结果,如果您想在某个包装器中打印对象,您可以执行以下操作:

var text = '{';

for(var i in data) {
  var value = data[i];

  text += '"'+i+'":"'+value+'", ';
}

text += '}';

$('#result').text(text);

But you may consider that console.logis much easier and faster way to see the response in json format.

但是您可能会认为这console.log是查看 json 格式响应的更简单快捷的方法。