提问者:小点点

无法从Ajax响应中找到特定的隐藏字段


我主要在后端工作,并试图在前端使用jQuery实现一些东西,这就是我正在努力实现的。

  1. 作为Ajax响应的一部分从后端传递URL.
  2. 从Ajax响应解析URL并执行一些附加操作。

这就是我的响应HTML的样子:(我不能改变HTML的结构)

<html>
<head>
    <title>Test Me</title>
</head>
<body>
<input type="hidden" id="confirmationURL" name="confirmationURL" value ="www.myurl.com"/>
</body>
</html>

这就是我试图解析和获取confirmationurl值的方式

success: function (res) {
  
    if (xhr.getResponseHeader('RESPONSE') === "true") {
      
        var $response = $(res);
        alert($response.find('#confirmationURL').text());
        //alert($(res).contents().find("#confirmationURL").text());
        var $result = $(res).contents().find('#confirmationURL')
        console.log($result.attr("confirmationURL").html());
        alert($(res).contents().find('#confirmationURL').text())

    }
    // some other stuff
}

我甚至尝试了filter选项,但对于所有选项,我都得到了空值或未定义。 我不确定这是否正确,因为我尝试了所有这些选择,通过不同的帖子,一个建议。 有人能给我指出正确的方向吗?我做错了什么,才能得到确认url


共1个答案

匿名用户

问题是因为在您接收的HTML的body中没有包含元素的父元素。 因此,在尝试从结果DOM的顶层检索输入时,需要使用filter()

此外,您需要读取它的,而不是它的innerText或innerHTML,因此使用val():

null

let res = '<html><head><title>Test Me</title></head><body><input type="hidden" id="confirmationURL" name="confirmationURL" value="www.myurl.com"/></body></html>';

var $response = $(res);
console.log($response.filter('#confirmationURL').val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>