简体   繁体   中英

When to escape data being sent with AJAX

I need to escape text that is being outputted via AJAX. If I submit script to the database, like <script>alert('hello world');</script> , then a popup is executed on the page.

This here is my function that is setting the data, and then grabbing data to be sent via AJAX.

function add_order() {
    if($_SERVER['REQUEST_METHOD'] == "POST") {
        $add_order = $this->order_model->set_order($_POST['text']);
        if($add_order==false){
            echo "fail";
            return false;
        }
        $order_data = $this->order_model->get_order_by_id($add_order);
        echo json_encode($order_data);
        return true;
    }
}

Jquery Code:

$('#create_order').submit(function(){
        $.post('/order/add_order/', $('#create_order').serialize(), function(data){
            var obj = $.parseJSON(data);
            var obj_item = obj[0];
            $('tr.'+obj_item.id).append("<td>" + obj_item.text + "</td>");
            msg('success', 'Part #'+obj_item.number+' has been successfully created');
        });
    }
    return false;
});

How do I stop obj_item.text from executing scripts?

您需要构建DOM元素并设置文本,而不是构建HTML:

$("<td />", { text: obj_item.text }).appendTo('tr.tr.' + obj_item.id);

If the submitted data can only contain plain text, ensure that you use .text() to re-insert it back into the DOM - using .text will prevent any embedded tags from being rendered as HTML or otherwise handled by the browser.

You should also validate data on the server before it's stored, and for extra measure perform client-side verification before posting the data to the server. IMHO, it's better to reject bad data than to simply escape it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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