$.ajax函数在向web服务发送JSON对象时失败


$.ajax function fails when sending JSON object to web service

我已经装入了一个示例web服务来存储和检索数据。PHP web服务有两个名为getData.PHP和saveData.PHP的脚本,getData返回json响应,saveData将json对象保存到数据库中。

getData.php

<?php
    require_once ('../database.php');
    mysqli_select_db($conn, $database);
    $query = "SELECT * FROM user ORDER BY id ASC";
    $result = mysqli_query($conn, $query) or die(mysqli_error($conn));
    $rows = array();
    while($packages = mysqli_fetch_assoc($result)) {
        array_push($rows, $packages);
    }
    header('Content-type: application/json');
    echo json_encode($rows);
?>

saveData.php

<?php
    require_once ('../database.php');
    mysqli_select_db($conn, $database);
    if (isset($_POST['json'])) {
        $jsonObj = $_POST['json'];
        $jsonObj = json_decode($jsonObj);
        $query = "INSERT INTO user (first_name, last_name, description)"
                . " VALUES ('".$jsonObj->{'first_name'}."', '".$jsonObj->{'last_name'}."', '".$jsonObj->{'description'}."')";
        mysqli_query($conn, $query);
        header('Content-type: application/json');
        echo json_encode($_POST['json']);
    }
?>

这是在我的wamp/www文件夹中的一个名为testService的文件夹中。然后我有另一个名为testConsume的文件夹,其中有一个带有简单表单的html页面,该表单将数据发送到testService/saveData.php文件。

HTML

<form role="form">
    <div class="form-group">
        <input name="first_name" id="txtFirstName" class="form-control" placeholder="First Name" type="text" />
    </div>
    <div class="form-group">
        <input name="last_name" id="txtLastName" class="form-control" placeholder="Last Name" type="text" />
    </div>
    <div class="form-group">
        <input name="description" id="txtDescription" class="form-control" placeholder="Description" type="text" />
    </div>
    <a id="submit" class="btn btn-success" onclick="sendData()">Submit</a>
</form>

在脚本中,sendData()函数获取数据并将其作为json对象发送

function sendData() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var description = $('#txtDescription').val();
    var jqxhr = $.ajax({
            url: 'http://localhost:8080/testService/json/saveData.php',
            type: 'POST',
            contentType: 'application/json',
            data: { json: JSON.stringify({
                first_name: firstName,
                last_name: lastName,
                description: description
            })},
            dataType: 'json'
        });
    jqxhr.done(function() {
        alert("Success! " + firstName + " " + lastName + " is a " + description);   
    });
    jqxhr.fail(function() {
       alert("Failed"); 
    });
}

当我运行testConsume/index.html并单击submit时,会显示警告消息Failed。当我检查数据库时,没有添加任何数据。我做错了什么?

删除contentType: 'application/json'

您发送的是嵌入在application/x-www-form-urlencoded数据中的JSON,而不是纯JSON。


或者。发送和解析实际的纯JSON:

contentType: 'application/json',
data: JSON.stringify({
    first_name: firstName,
    last_name: lastName,
    description: description
}),

在你的PHP中:

if (stripos($_SERVER["HTTP_CONTENT_TYPE"], "application/json")===0) {
    $jsonObj = json_decode(file_get_contents("php://input"));
}