1

为什么我的代码不起作用?

我知道我正在发送数据,

但是没有回应。

jQuery

    $(document).ready(function(){
            $("form").submit(function () {

                var uname = document.getElementById("username").value;
                var pword = document.getElementById("password").value;
                var postData = {
                    username: uname,
                    password: pword
                };
                var PostDataString = JSON.stringify(postData);
                alert(PostDataString);

            $.ajax({
               url: "test.php",
               type: "GET",
               data: PostDataString,
               dataType: 'json',
               contentType: 'json',
               cache: false,
               success: function (ReturnData) {
                    alert("Yay!");
               } 
            });
    });
    });

PHP

$json = $_GET["PostDataString"];
$jsonarray = json_decode($json, true);
echo $jsonarray;  

4

1 回答 1

4

json_decode用于将 JSON 字符串转换为 PHP 结构。 json_encode做相反的事,是你想要的。您期望在 JavaScript 端使用 json 数据类型;如果在这种情况下 jQuery 没有得到有效的 JSON,它会抛出一个错误。

JSON.stringify转换是不必要的,因为它的属性$.ajax接受一个 JavaScript 对象。data事实上,对 JSON 进行字符串化可以防止它作为任何参数发送。

如果您删除并按原样JSON.stringify发送。postData您可以访问$_GET['username']$_GET['password'],但不能访问其他人。

于 2013-02-07T03:04:13.527 回答