清理AJAX响应,以更新“选择框"中的选项 [英] Sanitize AJAX Response that updates Options in Select Box

查看:70
本文介绍了清理AJAX响应,以更新“选择框"中的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有BloggersBlogs.每个blog与一个blogger相关联.这是Blog记录的图片:

I have Bloggers and Blogs. Each blog is associated to a blogger. Here is a picture of the Blog records:

请注意,Jennell的第一个blog属性的title属性具有某些javascript,如果在某些情况下未正确进行清理,则可能会触发该javascript.

Notice that the title attribute of Jennell's first blog has some javascript that could be triggered if not sanitized properly in certain situations.

这正是这些情况之一.我有两个选择框:

Here is exactly one of those situations. I have two select Boxes:

对于第一个选择框:用户选择一个Blogger.发生这种情况时:

For the first select box: the user picks a Blogger. When this happens:

  • 一个AJAX请求被发送到服务器,以获取与所选Blogger
  • 相关的所有Blogs
  • 服务器将所有关联的blogs捕获到该blogger并将它们发送回请求者
  • 针对ajax请求的响应会删除Blog选择框
  • 中的所有选项
  • 然后,对ajax请求的响应作为选项添加到Blog选择框中,将所有在服务器上获取的blogs捕获.
  • an AJAX request gets sent to the server to grab all of the associated Blogs for that selected Blogger
  • the server grabs all the associated blogs to that blogger and sends them back to the requester
  • The response for the ajax request removes all options within the Blog select box
  • The response for the ajax request then adds in as options in that Blog select box all the blogs that were grabbed on the server.

名为Jennell的Blogger有一个关联的blog和一个包含JavaScript hack的title.因此:当Jennell 被选中:

The Blogger named Jennell has an associated blog with a title that contains a javascript hack. Thus: when the Jennell Blogger gets selected:

与她相关的Blog内的骇客将被执行:

That hack within her associated Blog will get executed:

这是AJAX请求的实际代码:

Here is the actual code for the AJAX request:

$("body").on('change', '[data-action="blogger_sel"]', function() {
  var blog_sel = $(this).closest('[data-parent-for="blog_sel"]').find('[data-action="blog_sel"]');
  $.ajax({
    url: "/blogs",
    type: "GET",
    data: {blogger_id: $(this).val()},
    success: function (data) {
      blog_sel.children().remove();
      $.each(data, function (index, value) {
        /* DO NOT APPEND THIS WAY.  VULNERABLE TO USER-ENTERED JAVASCRIPT EXECUTING */
        blog_sel.append('<option value=' + value.id + '>' + value.title + '</option>');
      });
    }
  })
});

AJAX请求中的问题是此部分:

The issue in the AJAX request is this part:

value.title

我需要对其进行消毒.

问题:在AJAX响应中:如何清理value.title?

Question: Within the AJAX response: how can I sanitize value.title?

推荐答案

通过属性而不是html字符串设置文本/值.

Set the text/values via attributes, not the html string.

var str = "<script>alert('x');<\/script>Test",
    opt = $("<option></option>", { "text" : str, value : "foo" });
$("select").append(opt);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>

这篇关于清理AJAX响应,以更新“选择框"中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆