简体   繁体   中英

Reload meta tag after ajax request - jQuery

How do I reload a specific meta tag (being generated by php) after an Ajax request?

The tag :

<meta name="csrf-token" content="efca1389c7f2323c875f3197ead688e9206d8835e10ef618e1241faac2dc750e">

The method I'm trying in the Ajax success response (which isn't working) :

$("meta[name=csrf-token]").load(location.href+" meta[name=csrf-token]>*","");

I'm pretty sure I'm selecting it wrong but can't find the correct approach. Can anybody help?

The issue is that load() populates the content of the tag you target. This isn't what you want to do. Instead you need to update an attribute of the tag, or just replace the entire tag with the updated one you retrieve from an AJAX request.

You can achieve the latter like this:

$.ajax({
  url: location.href,
  success: function(html) {
    var newMeta = $(html).find('meta[name="csrf-token"]')
    $('meta[name="csrf-token"]').replaceWith(newMeta);
  },
  error: function(x, s, e) {
    console.log('Something went wrong...');
  } 
});

You can do something like this:

var metaTag = document.querySelector('[name="csrf-token"]');
metaTag.setAttribute('content', yourNewDescriptionContent);

Assuming that the content is the property from the element you want to change.

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