Javascript 返回的Ajax响应声明其属性值未定义
我有两个JS文件,一个包含一个通用函数列表,在多个名为form.JS的文件之间共享,另一个特定于我的CMS上的某个页面,名为blog.form.JS 在form.js中,我有一个通用的js函数,每当我请求从数据库加载记录时,它都会发出jQuery.ajax请求:Javascript 返回的Ajax响应声明其属性值未定义,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有两个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 f
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_记录内的调试警报语句alert response.link++response++response.response TEXT返回以下内容:未定义的[Object XMLHTTPRequest]{link:http://www.url.com}
因此,另一个函数中的调试警报语句alert response.link也返回undefined
已成功返回XMLHTTPRequest对象。那么,为什么response.link声明它的值是未定义的呢
非常感谢您的帮助。您想做什么
alert response.link++response++response.responseText
成功函数的内部。你也不想
var响应=$.ajax
您只需调用ajax
$.ajax
Ajax是异步的,除非您告诉它不要异步,这意味着请求可以随时返回。尝试在success函数之外使用响应是没有意义的,除非您将其包装成闭包或将其作为参数传递。成功在响应成功完成时触发,只有在该函数中才会定义响应。您完全正确,可以创建一个返回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 );
});
});
警报响应.link++response++response.responseText;in load_记录将保持原样返回,除非您将其添加到success或done处理程序中
如果您需要更多关于什么是“完成”的信息,请查看jquerys网站上的延迟和上面的链接。我希望这会有所帮助。那么,有没有办法将成功函数中返回的响应与另一个JS文件中的函数共享?这就是我的问题,我在文件1中的一个通用函数中返回了一个响应,我需要使该响应对文件2中的特定函数可用。当然,只需调用该函数,并将响应作为参数传递。哦,但问题是blog.form.js是链接的,需要在通用form.js文件之后链接,因此,如果我在success函数中调用该函数,它将是一个无效的调用,因为该函数尚未定义。这是一个好方法!非常感谢你的提示和启示。