简体   繁体   English

Ajax发布到php的撇号问题

[英]apostrophe issue with ajax post to php

i am posting data with jquery ajax to php but if input has ' inside, data wont be posted. 我正在使用jquery ajax将数据发布到php,但是如果输入内容为' ,则不会发布数据。 I tried encodeURIComponent but wont work. 我尝试了encodeURIComponent但无法正常工作。

any idea on this ? 有什么想法吗?

thanks 谢谢

EDIT: my code 编辑:我的代码

var name = $("input#name_add").val();
         name = encodeURIComponent(name);

$.post("function.php", { name: name }, function(data) {

                               //codes
                });



$query = "UPDATE `table` SET name = '" . stripslashes($_POST['name']) . "' WHERE ID = '$id'";
$result = mysql_query($query);
if ($result){
print "ok";

}

encodeURIComponent不编码撇号,请尝试以下操作:

encodeURIComponent(str).replace("'", "%27");

Try checking the magic quotes setting on your server with get_magic_quotes_gpc() . 尝试使用get_magic_quotes_gpc()检查服务器上的魔术引号设置。 If it's on you need to strip_slashes() before using using mysql_real_escape_string() . 如果启用, strip_slashes()在使用mysql_real_escape_string()之前需要strip_slashes() mysql_real_escape_string()

Check the get_magic_quotes_gpc() documentation for an example. 请查看get_magic_quotes_gpc()文档中的示例。

If magic_quotes_gpc is off why are you stripping slashes in your query? 如果magic_quotes_gpc关闭,为什么要在查询中去除斜杠?

Try: 尝试:

$query = "UPDATE `table` SET name = '" . mysql_real_escape_string($_POST['name']) . "' WHERE ID = '$id'";

If you're using POST you shouldn't need to escape the data before passing it, but by using stripslashes in your code for the mysql you're gonna cause problems with any apostrophes as then your sql won't be escaped. 如果您使用的是POST,则在传递数据之前无需转义数据,但是通过在mysql代码中使用反斜杠,将导致任何撇号问题,因为您的sql不会转义。

This is what solved it for me. 这就是为我解决的问题。 Since the JavaScript encodeURIComponent() function does not encode apostrophes to %27, I did it myself using my own replaceAll() function. 由于JavaScript encodeURIComponent()函数不会将撇号编码为%27,因此我自己使用自己的replaceAll()函数进行了编码。

JS Snippet: JS代码段:

name = encodeURIComponent(name.replaceAll("'", '%27'));

This is the replaceAll() function in my utilities JS file : 这是我的实用程序JS文件中的replaceAll()函数:

String.prototype.replaceAll = function(f, r, no_escape) {
    var rexp = new RegExp(Util.EscapeRegExp(f), 'g');
    if (no_escape) { rexp = new RegExp(f, 'g'); }
    return this.replace(rexp, r);
};

For my purposes, I needed the apostrophe to not be %27 anymore, and the PHP function urldecode() does not do apostrophes either, so I used str_replace() to take care of that. 出于我的目的,我不再需要将撇号改为%27,并且PHP函数urldecode()也不执行撇号,因此我使用str_replace()来解决这一问题。

PHP Snippet : PHP代码段

$name = str_replace('%27', "'", urldecode($_POST['name'] ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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