解析JSON字符串时PHP中未定义的索引错误

时间:2022-10-17 09:00:50

I have my HTML file like this:

我有这样的HTML文件:

<script>
$(document).ready(function () {
   $("#btn").click( function() {
     var id = $('#id').val();
     var name =  $('#name').val();
     var Address = $('#Address').val();
     $.ajax({
        url: "http://localhost/connection.php",
        type: "POST",
        data : { topost: JSON.stringify({id: id, name: name, Address: Address}) },
        //I ASSUME HERE IM PASSING MY THREE FIELDS id, name and Address 
        //IN A STRING CALLED 'TOPOST' TO MY FILE CONNECTION.PHP
        //WHICH IS HOSTED ON MY LOCALHOST, IM USING XAMPP.
        datatype: "jsonp",
        success: function (status) {
            if (status.success == false) {
                alert("Failure!");
            }
            else {
                alert("Success!");
            }
        }
     });
     return false;
   });
});
</script>

Now, in my file connection.php, which is hosted on my localhost, I'm trying to read these three fields so that I can put all three in a database (MySQL).

现在,在我的本地主机上托管的文件connection.php中,我正在尝试读取这三个字段,以便我可以将所有三个字段放入数据库(MySQL)中。

However, the error I get is this:

但是,我得到的错误是这样的:

Connected to database!<br />
<b>Notice</b>:  Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>:  Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>29</b><br />

My question is:

Why is 'topost' undefined? How do I make connection.php understand that I'm sending JSON data from my HTML file in a variable called 'topost'?

为什么'topost'未定义?我如何使connection.php明白我从我的HTML文件中发送一个名为'topost'的变量中的JSON数据?

So kindly go through the following PHP file and suggest the errors.

请仔细阅读以下PHP文件并提出错误建议。

The server side PHP file:

<?php
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    $server = "localhost";
    $username = "root";
    $password = "";
    $database = "jqueryex";
    $con = mysql_connect($server, $username, $password);
    if($con) { echo "Connected to database!"; }
    else { echo "Could not connect!"; }
    //or die ("Could not connect: " . mysql_error());
    mysql_select_db($database, $con);
    $posteddata = $_POST['topost'];
    $thedata= json_decode($_POST['topost']);
    echo ($thedata);
    mysql_close();
?>

1 个解决方案

#1


0  

Your POST body needs to be url-encoded, not in JSON format. See the following question:

您的POST主体需要进行url编码,而不是JSON格式。请参阅以下问题:

Query-string encoding of a Javascript Object

Javascript对象的查询字符串编码

And here's some more information and an example of a POST body:

这里有一些更多的信息和一个POST主体的例子:

http://www.jmarshall.com/easy/http/#postmethod

So in your case, your code should look like this:

因此,在您的情况下,您的代码应如下所示:

$.ajax({
    url: "http://localhost/connection.php",
    type: "POST",
    data: $.param({
        topost: encodeURIComponent(
            JSON.stringify({id: id, name: name, Address: Address})
        )
    });
    datatype: "jsonp",
    success: function (status) {
        if (status.success == false) {
            alert("Failure!");
        } else {
            alert("Success!");
        }
    }
});

An additional note: you're specifying "jsonp" as the datatype, which means your script should wrap an object response in a function call consistent with how jsonp works. Another option is adding a CORS header (Access-Control-Allow-Origin) to your PHP responses to allow XMLHttpRequest connections to it in browsers that support Origin checking against CORS.

另外需要注意:您将“jsonp”指定为数据类型,这意味着您的脚本应该在函数调用中包装对象响应,与jsonp的工作方式一致。另一种选择是在PHP响应中添加CORS头(Access-Control-Allow-Origin),以允许在支持针对CORS的Origin检查的浏览器中与XMLHttpRequest连接。

See the jQuery.ajax() documentation for more information on the JSONP datatype: http://api.jquery.com/jQuery.ajax/

有关JSONP数据类型的更多信息,请参阅jQuery.ajax()文档:http://api.jquery.com/jQuery.ajax/

#1


0  

Your POST body needs to be url-encoded, not in JSON format. See the following question:

您的POST主体需要进行url编码,而不是JSON格式。请参阅以下问题:

Query-string encoding of a Javascript Object

Javascript对象的查询字符串编码

And here's some more information and an example of a POST body:

这里有一些更多的信息和一个POST主体的例子:

http://www.jmarshall.com/easy/http/#postmethod

So in your case, your code should look like this:

因此,在您的情况下,您的代码应如下所示:

$.ajax({
    url: "http://localhost/connection.php",
    type: "POST",
    data: $.param({
        topost: encodeURIComponent(
            JSON.stringify({id: id, name: name, Address: Address})
        )
    });
    datatype: "jsonp",
    success: function (status) {
        if (status.success == false) {
            alert("Failure!");
        } else {
            alert("Success!");
        }
    }
});

An additional note: you're specifying "jsonp" as the datatype, which means your script should wrap an object response in a function call consistent with how jsonp works. Another option is adding a CORS header (Access-Control-Allow-Origin) to your PHP responses to allow XMLHttpRequest connections to it in browsers that support Origin checking against CORS.

另外需要注意:您将“jsonp”指定为数据类型,这意味着您的脚本应该在函数调用中包装对象响应,与jsonp的工作方式一致。另一种选择是在PHP响应中添加CORS头(Access-Control-Allow-Origin),以允许在支持针对CORS的Origin检查的浏览器中与XMLHttpRequest连接。

See the jQuery.ajax() documentation for more information on the JSONP datatype: http://api.jquery.com/jQuery.ajax/

有关JSONP数据类型的更多信息,请参阅jQuery.ajax()文档:http://api.jquery.com/jQuery.ajax/