简体   繁体   中英

jQuery selecting data value from fetch

I came across another issue with jquery. I seen code that uses .ajax() method and the response is being selected like this

.then(response => {
  $(response).find('.some-selector')
})

This is really confusing me.

I did a refactor to vanilla js like this

fetch('/some-endpoint', {
  method: 'POST',
  body: new FormData(e.currentTarget)
})
.then(res => res.text())
.then(data => {
  data.querySelector('.some-selector') // does not work
})

Everything is working, the response is good, but I do not understand how to get the selected value from the data.

You need to parse the response first:

 fetch('/some-endpoint', { method: 'POST', body: new FormData(e.currentTarget) }) .then(res => res.text()) .then(function(html) { const parser = new DOMParser(); return parser.parseFromString(html, "text/html"); }) .then(data => { data.querySelector('.some-selector'); })

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