这可能很容易,但我很难做好这件事。如何使用jquery ajax响应在同一窗口中打开新页面?
正如您所看到的,如果php响应等于单词"invalid",我将尝试显示一个自定义文本。如果没有,请在同一窗口中打开一个新的html页面。
$("#lBtn").click(function(){
$.post("php/session.php",
{ username:$("#username").val(),
password:$("#password").val()
},
function(response) {
alert(response)
if(response == "invalid"){
$("#loginResponse").text("Error!!");
} else {
window.location = $(this).find('new/pahe.html').html();
}
});
});
Alert(response)显示单词"invalid",但if语句无效。意味着它既不在$("#loginResponse")
中显示Error!!
,也不打开新页面。这就是我想要解决的问题。
您可能会在post的输出中返回额外的空白(可能是回车还是空格?)。
微调响应:
function(response) {
response = $.trim(response);
if(response == "invalid"){
或者这样做只是为了检查子字符串是否匹配:
function(response) {
if(response.indexOf("invalid")>=0){
编辑:你的问题用词不对。您的目标是重定向到另一个页面。
如果#lBtn
的html是url本身,那么解决方案是使用:
window.location.href = $(this).html();
这是用于打开新标签中的链接
首先创建一个隐藏在某处的新链接:
Javascript代码
$('body').append('<a id="new_wnd_temp" href="another_page.html" target="_blank" style="display:none"></a>');
然后触发点击事件:
Javascript代码
$('#new_wnd_temp').trigger('click').remove();
在您的示例中,它看起来是这样的:
Javascript代码
$("#lBtn").click(function() {
$.post("php/session.php", {
username:$("#username").val(),
password:$("#password").val()
},
function(response) {
alert(response);
if(response == "invalid") {
$("#loginResponse").text("Error!!");
} else {
$('body').append('<a id="new_wnd_temp" href="another_page.html" target="_blank" style="display:none"></a>');
setTimeout(function () {
$('#new_wnd_temp').trigger('click').remove();
}, 0);
}
});
});