返回的 Ajax 响应指出其属性值未定义

Ajax response returned stating its property values are undefined

本文关键字:属性 未定义 Ajax 响应 返回      更新时间:2023-09-26

我有 2 个 JS 文件,一个包含一个名为"form.js"的多个文件之间共享的通用函数列表,另一个特定于我的 CMS 上名为"blog.form.js"的某个页面。

在"form.js"中,我有一个通用的JS函数,每当我请求从数据库加载记录时,它都会发出jQuery.ajax((请求:

function load_record( field_id, class_name, entity_type ) {
// Send ajax request to load the record, and enable the form's state once the record's content has been received.
var response = $.ajax({
    async: false,
    dataType: "json",
    data: {
        action: "load_"+entity_type,
        id: $("#"+field_id+"_list").val()
    },
    success: function(response) {
        // Make visible the buttons to allow actions on record, such as deleting or renaming.
        $("#"+field_id+"_actions").show();
        // Make visible the container of all form elements related to the record.
        $("#"+field_id+"_form_inputs").show();
        // Must return response so the calling JS file can use the values returned to
        // populate the form inputs associated with the record that's just been loaded
        // with the correct values.
        return response;
    },
    type: "post",
    url: "/ajax/record/"+class_name
});
alert( response.link + " " + response + " " + response.responseText);
return response;

}

在"blog.form.js"中,当我从包含数据库记录列表的菜单中选择要加载的数据库记录时,我调用了函数:

// Select a link for editing.
$("#links_list").live( "change", function(){ 
    // Insert response returned from function call to load the db record into a variable.
    // This is so the form inputs associated with the record loaded can be populated with the correct values. 
    var response = load_record('links_edit', 'blog', 'link'); 
    alert( response.link );
    $("#links_edit_url").val( response.link );        
});

ajax 请求返回所需的响应。不幸的是,load_record(( 中的调试警报语句 "alert( response.link + " " + response + " " + response.responseText(" 返回以下内容:undefined [Object XMLHTTPRequest] {"link": "http://www.url.com"}。

因此,另一个函数中的调试警报语句"alert( response.link ("也返回未定义。

XMLHTTPRequest 对象已成功返回。那么,为什么 response.link 声明其值是未定义的呢?

任何帮助都非常感谢。

你完全走在正确的轨道上,你可以创建一个返回ajax对象的函数。 jQuery将该ajax调用作为延迟对象返回 - 因此它有额外的方法来事后利用ajax响应。

$("#links_list").live( "change", function(){ 
    load_record('links_edit', 'blog', 'link').done( function( response ) {
        alert( response.link );
        $("#links_edit_url").val( response.link );     
    });
});

load_record 中的alert( response.link + " " + response + " " + response.responseText);将继续按原样返回,除非您将其添加到成功或完成处理程序中。

如果你需要更多关于.done()到底是什么的信息,请查看jquerys网站上的Deferreds,上面的链接。我希望这有所帮助。

你想做的

alert( response.link + " " + response + " " + response.responseText);

在成功函数内部。 你也不想

var response = $.ajax(...

你只是调用 ajax...

$.ajax(...

Ajax 是异步的(除非你告诉它不要异步(,这意味着请求可以随时返回。 尝试在 success 函数之外使用响应是没有意义的(除非您在它周围包装一个闭包或将其作为参数传递(。 success响应完成(成功(时触发,则仅在该函数中定义response