【问题标题】:Escaping String in JQuery on .ajax submit to submit to mySQL在.ajax提交上的JQuery中转义字符串以提交到mySQL
【发布时间】:2025-11-23 04:15:01
【问题描述】:

我有一个简单的 HTML 表单,我必须使用 JQuery.ajax 提交。

<form id="myForm" name="myForm" action="mySite/data.php" method="post">
    <label for="name">Name: </label>
    <input type="text" id="name" name="name" size="30"/>
    <label for="text">Text:</label> <br/>
    <textarea class="required textarea" cols="60" id="request" name="request"  </textarea>
    <br/>
    <input type="submit" id="submit" name="submit" value="Submit"/>
    <input type="reset" value="Clear"/>
</form> 

还有 JQuery.ajax:

<script type="text/javascript">
  var frm = $('#myForm');
  frm.submit(function () {
    if(frm.valid() == true){
         $.ajax({
              type: frm.attr('method'),
              url: frm.attr('action'),
              data: frm.serialize(),
              success: function (data) {
                    alert("Your Request Has Been Received. Thank You.");
                }
            });  
    } else {
        alert("Please Enter a Valid Request");
    }
    return false;
    });   
</script>

表单数据保存到 mySQL 数据库,然后使用更多 JQuery.ajax 显示在另一个页面上。在这些页面和数据库之间,我有 php 页面来读取和写入数据,这里:

switch($_REQUEST['action'])
{
case "submit":
    addRequest($_GET['name'], $_GET['content']);
    header('Location: myPage.html'); 
    break;

}

if(isset($_POST['request'])){
$content = stripslashes($_POST["request"]);

echo "<h3>Here is the Request You Just Entered: </h3><br/>";
echo "<table width=40%><tr><td style='font-weight:bold;'>Name: </td><td>" . $name . "</td></tr>" .   "<tr><td style='font-weight:bold;'>Your Request: </td><td>" . $content . "</td></tr></table>";
$name = addslashes($name);
$content = addslashes($content);

echo "<br/><a style='padding-right:3%;' href='?action=submit&name=" . $name . 
         "&content=" . $content . "'>Submit Request</a>";

echo "<a href='javascript:history.back()'>Back to the Site</a>";

die();
} else {
echo "No Data Submitted";
}
?>

页面正确显示了所有内容,但是当我显示发送到我的 addRequest() 函数的信息时,数据没有转义,这会导致问题。

除非文本输入需要转义,否则一切都很好。我已经调试了系统,发现在我使用 JQuery 提交表单数据之前需要对我的字符串进行转义。

我该如何正确地做到这一点,或者我的问题有什么不同?提前感谢您的帮助。

【问题讨论】:

  • “在我使用 JQuery 提交表单数据之前,我的字符串需要转义” - 不,因为有人可以绕过它。在 mysql 查询之前转义为 mysql,在显示 html 之前为 html 转义。
  • 是的,这是真的,但问题是如果我的字符串在调用函数之前没有转义,那么它会导致函数本身出现问题。你有什么建议?

标签: php jquery escaping form-submit


【解决方案1】:

您不需要在 jQuery 中转义任何内容,因为 .serialize() 负责正确编码所有内容。

但是,在锚标记中创建 URL 时需要进行 URL 编码:

echo "<br/><a style='padding-right:3%;' href='?action=submit&name=" . urlencode($name) . 
     "&content=" . urlencode($content) . "'>Submit Request</a>";

【讨论】:

    【解决方案2】:

    这是一个在 Jquery 中转义的函数:

    function addslashes(string) {
    return string.replace(/\\/g, '\\\\').
        replace(/\u0008/g, '\\b').
        replace(/\t/g, '\\t').
        replace(/\n/g, '\\n').
        replace(/\f/g, '\\f').
        replace(/\r/g, '\\r').
        replace(/'/g, '\\\'').
        replace(/"/g, '\\"');
    }
    

    【讨论】: