php - 清理数据以在引号内和 URL 内使用

标签 php javascript encoding sanitization

如果我想在 Javascript 中将一个值放在单引号之间,我该如何对其进行清理/编码,以便该值中的任何引号都不会引起问题?

然后我还想在查询字符串中使用该值,然后将其传递给 PHP。

无论使用什么,我都需要能够使用 PHP 将其解码回正常值。

示例:

$foo = "Hey, what's up!?"; // PHP

getGrades('<?=$foo?>'); // JS Function

function getGrades(var) {

        // Set file to get results from..
        var loadUrl = "ajax_files/get_grades.php";

        // Set data string
        var dataString = 'grade=' + var;

        // Run the AJAX request
        runAjax(loadUrl, dataString);          

}

function runAjax(loadUrl, dataString) {

    jQuery.ajax({
        type: 'GET',
        url: loadUrl,
        data: dataString,
        dataType: 'html',
        error: ajaxError,
        success: function(response) {
            someFunction(response);
        }
    });    

}

// get_grades.php file

$grade = $_GET['grade']; // We now want this value to be it's normal value of "Hey, what's up!?";

最佳答案

getGrades('<?=$foo?>'); // JS Function

json_encode将使字符串 JavaScript 安全(并引用它)。

getGrades(<?php echo json_encode($foo); ?>);

I also want to then use this value in a query string which I will then be passing to PHP.

通过 data: 对象,而不是字符串。 jQuery 将为您处理转义。

var dataString = { grade: var }; // Rename the variable too

关于php - 清理数据以在引号内和 URL 内使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14213352/

相关文章:

php - 那么当我们在 PHP 中使用 'new' 时到底发生了什么

javascript - Ember.Select 更改前确认

javascript - 使用php浏览时写入文件的完整路径

android - 为 URI 使用编码图像

python - 将unicode转换为gsm字符的算法

php - XML 解析错误 : undefined entity - special characters

php - SQL INNER JOIN 未正确连接?

PHP:mcrypt 与非对称 openssl 用于加密两方之间的消息

javascript - 是否可以将映射集合名称的名称作为 MongoDB 映射函数中键的一部分包含在内?

html - 为什么 html 转义 >159?