0

我正在尝试获得成功响应,以将 ajax 中的值发送到各自的字段中。无论出于何种原因,我都无法做到这一点。在成功部分,我发出“alert(responseObject)”,其中结果在附加图像中。所以数据会按照我的意愿返回,但我无法将值填充到匹配的字段中。

$(document).ready(function() {
    function myrequest(e) {
        var man_part_number = $('#man_part_number').val();
        $.ajax({
            method: "GET",
            url: "includes/autofill.php",

            data: {
                man_part_number: man_part_number
            },
            success: function(responseObject) {
                alert(responseObject);
                //This alert response results is in attached image
                $('#manufacture').val(responseObject.manufacture);
                $('#model').val(responseObject.model);
                $('#type').val(responseObject.type);
            },
            failure: function() {
                alert('fail');
            }
        });
    }

    $('#fetchFields').click(function(e) {
        e.preventDefault();
        myrequest();
    });
});

<button type="button" id="fetchFields">Fetch</button>

<input type="text" name="manufacture" id="manufacture" />
<input type="text" name="model" id="model" />
<input type="text" name="type" id="type" />

返回 AJAX 代码

4

1 回答 1

2

返回的字符串不是JSON。在警报框中查看字符串的结尾。它有“测试”。这意味着响应被 jQuery 解析为文本,因为您没有指定dataType选项。如果您确实将其指定为“JSON”,它将失败,因为“{...}”旁边的“test”是无效的 JSON。我想重点是您需要返回有效的 JSON,如果您确实希望返回 JSON,请将调用的dataType选项设置为$.ajax“JSON”。同时,您的服务器无论如何都应该在响应中设置正确的标头。(有时)指定dataType选项仍然更好。

默认情况下,如果您不指定该dataType选项,jQuery 将检查响应的标头以获取 Content-Type。如果它与“JSON”、“HTML”、“Text”、“XML”或其他一些类型的有效类型匹配,它将尝试通过它来解析它。我打赌您的响应没有正确设置其标题,否则 jQuery 会尝试将其转换为 JSON 并失败。它可能以纯文本形式返回,因此 jQuery 会看到它并将其解析为文本……这就是它解析良好的原因。但是responseObject您引用的不是Object您所期望的,因为您没有遵循这些程序来确保正确解析。

于 2013-01-24T07:14:36.683 回答