Jquery Ajax返回400 BAD请求

时间:2017-02-23 12:42:02

标签: javascript php jquery mysql ajax

我正在尝试将数据发送到我的本地数据库服务器,但是当我尝试发送它时,我一直收到400 Bad request错误。

var studentEmail = "ali@gmail.com";
            var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;


            $.ajax({
            type: "POST",
            dataType:'json',
            url: "js/dbcon.php",
            data: JSON.stringify(dataString),
            processData: false,
            contentType: "application/json; charset=utf-8"
            });

这是php文件

<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>

谁能看到我做错了什么?

提前致谢!

4 个答案:

答案 0 :(得分:1)

JSON.stringify()方法用于将javascript object 转换为json字符串。

因此dataString变量必须是javascript object

var data ={questionNumber:temp ,answer: value ,email:studentEmail};

AJAX

$.ajax({
    type: "POST",
    dataType:'json',
    url: "js/dbcon.php",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=utf-8"
});

答案 1 :(得分:1)

如果您更改帖子,则必须将$ _POST替换为$ _GET到您的php文件中。

答案 2 :(得分:1)

有一种更简单的方法可以传递对POST和GET请求都能正常工作的数据

var studentEmail = "ali@gmail.com";
$.ajax({
        type: "POST",
        dataType:'json',
        url: "js/dbcon.php",
        data: {questionNumber:temp, answer:value, email: studentEmail},
        processData: false,

});

现在jQuery完成了所有艰苦的工作,并将充满数据的对象转换为POST或GET请求所需的任何格式

答案 3 :(得分:1)

您可以通过以下方式发送ajax个请求:

var studentEmail = "ali@gmail.com";
            $.ajax({
            type: "POST",
            dataType:'json',
            url: "js/dbcon.php",
            data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
            processData: false,
            contentType: "application/json; charset=utf-8"
            });

此外,PHP文件也需要返回json字符串。

echo "succesfully posted";

无效json答案。

返回这样的内容:

$arr = array('success' => true, 'answer' => "succesfully posted");

echo json_encode($arr);

另见:http://php.net/manual/de/function.json-encode.php

在插入数据库之前,您应该验证输入数据。