清理AJAX响应,以更新“选择框"中的选项 [英] Sanitize AJAX Response that updates Options in Select Box
问题描述
我有Bloggers
和Blogs
.每个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
捕获到该blogger
并将它们发送回请求者 - 针对ajax请求的响应会删除
Blog
选择框 中的所有选项
- 然后,对ajax请求的响应作为选项添加到
Blog
选择框中,将所有在服务器上获取的blogs
捕获.
Blogs
- an AJAX request gets sent to the server to grab all of the associated
Blogs
for that selectedBlogger
- the server grabs all the associated
blogs
to thatblogger
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 theblogs
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屋!