【发布时间】:2010-08-31 21:31:28
【问题描述】:
出于某种原因,IE 要求我们下载文件而不是作为 ajax 运行。这适用于除 IE 之外的所有浏览器。我尝试弄乱它没有运气返回的标题。
该函数获取表单数据,然后发布它,响应是一个可以是页面上要更新的任意数量项目的数组。
它不应该是文件,它应该只是一个 json 响应。
PHP
header('Content-type: application/json');
$error = "The Email and Password you entered could not be resolved.";
$elements[0]['target'] = '.error_report';
$elements[0]['action'] = 'inside';
$elements[0]['data'] = '<p>'.$error.'</p>';
$this->output->set_output(
json_encode(array("elements" => $elements))
);
Javascript
$(document).ready(function () {
jQuery.ajaxSetup({
cache: false,
dataType: 'json',
error: function () {
alert("Request was not successful. Please try again shortly.");
}
});
$(document).ajaxSuccess(function (e, xhr, settings) {
var response = xhr.responseText;
if (settings.dataType != 'json') {
return;
};
try {
response = jQuery.parseJSON(response);
} catch (e) {
alert(e);
return;
}
if (response.elements instanceof Array) {
var reqs = ['target', 'action'];
var valid = true;
for (var i=0;i<response.elements.length;i++) {
var cur = response.elements[i];
var sel;
for (var j=0;j<reqs.length;j++) {
if (typeof cur[reqs[j]] !== "string") {
valid = false;
break;
};
};
if (!valid) {
continue;
};
sel = $(cur.target);
switch (cur.action) {
case "inside":
sel.html(cur.data);
break;
case "instead":
sel.replaceWith(cur.data);
break;
case "remove":
sel.remove();
break;
case "refreshPage":
window.location.reload();
default:
if (typeof sel[cur.action] === "function") {
sel[cur.action](cur.data);
}; // else continue
break;
};
};
};
// Dispatch the AJAX request, and save it to the data object so that
// is can be referenced and cancelled if need be.
self.data('ajaxify.xhr', jQuery.ajax({
url: this.action,
type: 'post',
dataType: options.dataType,
data: (beforeSubmitIsJquery ? beforeSubmitResult.serialize()
: self.serialize()),
success: function (/**/) {
cleanup();
options.onSuccess.apply(that, arguments);
},
error: function (/**/) {
cleanup();
options.onError.apply(that, arguments);
},
complete: function (/**/) {
options.onComplete.apply(that, arguments);
}
}));
【问题讨论】:
-
您根本不需要内容类型。是什么触发了ajax请求?活动?
-
好吧,我问是因为您描述的行为具有由事件处理程序启动 ajax 请求随后“本机”浏览器表单引起的双重发布的所有特征提交发生。如果我是你,我会三重确保你的事件处理程序要么返回“false”,要么调用“preventDefault”,或者两者兼而有之:-)
-
作为一个临时实验,您可以尝试将
<button type="button">添加到您的表单,然后将您的处理程序仅连接到该表单。 “按钮”类型的按钮不会提交表单,所以如果它在您使用该测试按钮进行操作时有效,那么您有证据表明您在当前代码中没有以某种方式取消该事件。跨度> -
由于IE忽略了preventDefault,尝试在preventDefault之后使用
return false;... -
加油,@drachenstern,替我向什里夫波特说“嗨”
标签: php javascript jquery internet-explorer json