如果我想在 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/