[英]Why can't I modify the response of this post request via jQuery?
So I have a login form, that when submitted will redirect to the homepage /
.所以我有一个登录表单,提交后将重定向到主页
/
。
I would like the form to have the same behaviour except that when I receive the response back from the server, which comes in the form of HTML data, I can modify that HTML data so that after the redirect occurs, the homepage will show the modified HTML:我希望表单具有相同的行为,除了当我从服务器收到以 HTML 数据形式出现的响应时,我可以修改HTML 数据,以便在重定向发生后,主页将显示修改后的数据HTML:
$(#login-form).submit(function(event) {
event.preventDefault();
var $form = $(this);
var user = $("#username").val();
var passwd = $("#password").val();
var url = $form.attr("action");
var posting = $.post(url, { username: user, password: passwd });
posting.done(function(data) {
$(data).find("#logged-user").text("user777");
$('html').html(data);
});
});
In the above snippet of code, when say user111
logs in, then there's a span tag <span id="logged-user"></span>
that displays the name of the logged in user.在上面的代码片段中,当说
user111
登录时,会有一个跨度标签<span id="logged-user"></span>
显示登录用户的名称。
However, when I try to manipulate this span tag so it shows the name of a different user via $(data).find("#logged-user").text("user777");
但是,当我尝试操作此跨度标记时,它会通过
$(data).find("#logged-user").text("user777");
显示不同用户的名称。 it doesn't work.它不起作用。 Why?
为什么?
Try this:尝试这个:
posting.done(function(data) {
var tmp = $('<div>' + data + '</div>'); // Create a temporary DOM
tmp.find("#logged-user").text("user777"); // Modify it
$('html').html( tmp.html() ); // Get its HTML, and use it
});
or simply:或者简单地说:
posting.done(function(data) {
$('html').html(data);
$("#logged-user").text("user777");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.