简体   繁体   English

AJAX数据响应-如何解析HTML

[英]AJAX data response - how to parse html

I have this response in my AJAX request: 我的AJAX请求中有以下响应:

    <!DOCTYPE html>
    <html>
    <head>
    <title>AJAX request</title>
    <style type="text/CSS">
    * {
    font-family:Courier New;
    }
    </style>
    </head>
    <body>
    1
    </body>
    </html>

but in 但在

    $.ajax({
    ...
    complete:function(data){
    // data has only <title>AJAX request</title><style type="text/CSS">* {font-family:Courier New;} </style> 1
    }
    ...
    });

I can't parse it and how can I get 1 value from it? 我无法解析它,如何从中获得1个值? What I do wrong? 我做错了什么? I don't get all html tags, only title, style and content of body. 我没有得到所有的html标签,只有标题,样式和正文内容。 How can I fix it? 我该如何解决?

There is no need to send full HTML via AJAX, but only the data needed to modify the existing DOM because the response gets dropped right after the callback functions are done. 不需要通过AJAX发送完整的HTML,而仅需要修改现有DOM所需的数据,因为在完成回调函数之后,响应将立即被丢弃。

So, if you only need that value (1 in your case), you can send it only, so the full response of your AJAX call would simply be: 因此,如果只需要该值(在您的情况下为1),则只能发送该值,因此AJAX调用的完整响应将是:

1

and then your data variable would have the value of 1, of course. 然后您的data变量的值自然为1。

You can also use JSON (especially, if you're sending more data), like: 您还可以使用JSON(尤其是在发送更多数据时),例如:

{
  "value": 1,
  "somethingElse": "some value here"
}

etc. 等等

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

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