简体   繁体   English

在ajax响应中从html获取输入值

[英]get input value from html in ajax response

To get the html response of the page, I use: 要获取页面的html响应,我使用:

var theUrl = "https://example.com/users/22";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send();
var html = xmlHttp.responseText;

This will now return a 535 line html page. 现在,这将返回535行html页面。 If we simply had that source code on our current page, to get the value of the tag (12345) as shown below: 如果仅在当前页面上包含该源代码,则获取标记的值(12345)如下所示:

<input name="token" type="hidden" value="12345" />

we would simply use: 我们将简单地使用:

document.getElementsByName("token")[0].value;

But since the HTML is in the ajax response as a variable named html how do I get the value of the input with name token? 但是由于HTML在ajax响应中是一个名为html的变量,我如何获得带有名称标记的输入值? Can I somehow convert it to a DOM element and then run that code? 我可以以某种方式将其转换为DOM元素,然后运行该代码吗? javascript only please, no jQuery. 请只使用javascript,不要使用jQuery。 Thanks. 谢谢。

Try creating an HTML element, adding the response, and then parse it. 尝试创建一个HTML元素,添加响应,然后解析它。 We need to add a class name to select specific inputs with getElementsByClassName , or, if you want to select all inputs, you could use getElementsByTagName 我们需要添加一个类名以使用getElementsByClassName选择特定的输入,或者,如果您想选择所有输入,则可以使用getElementsByTagName

var responseText = '<input name="token" class="token" type="hidden" value="12345" />'
var el = document.createElement( 'html' );
el.innerHTML = responseText;
console.log(el.getElementsByClassName("token")[0].value); 

You can parse your xmltHttp.response text like this: 您可以这样解析您的xmltHttp.response文本:

  var xmlString = "<input name='token1' type='hidden' value='12345' />"; // Use your xmlHttp.responseText here. This is for demonstration purposes var parser = new DOMParser(); var element = parser.parseFromString(xmlString, "text/html"); console.log(element.querySelectorAll('[name="token1"]')[0].value); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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