简体   繁体   中英

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:

$(#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.

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"); 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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM