繁体   English   中英

jQuery Ajax返回400 BAD请求

[英]Jquery Ajax returns 400 BAD request

我正在尝试将数据发送到本地数据库服务器,但是在尝试发送数据时却不断收到400错误的请求错误。

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
?>

谁能看到我在做什么错?

提前致谢!

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"
});

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

有一种更简单的方法来传递对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请求所需的任何格式

您可以通过以下方式发送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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM