在php中从url获取参数会添加特殊字符
我有一个javascript代码,它调用PHP api的函数在数据库中插入一行在php中从url获取参数会添加特殊字符,php,url,parameters,character,add,Php,Url,Parameters,Character,Add,我有一个javascript代码,它调用PHP api的函数在数据库中插入一行 var url = 'http://myapi/OfertasVentaOnline/api.php?method=update&function=categoria&id='+id+'&idCategoria='+id_categoria+'&descripcion='+descripcion+'&format=json'; $.getJSON(url, func
var url = 'http://myapi/OfertasVentaOnline/api.php?method=update&function=categoria&id='+id+'&idCategoria='+id_categoria+'&descripcion='+descripcion+'&format=json';
$.getJSON(url, function (data){
});
此url的示例:
"http://myapi/OfertasVentaOnline/api.php?method=create&function=categoria&id=9999&idCategoria=3&descripcion=test%new%category&format=json"
在url中,我在Description参数中替换了%的空格,如图所示,url已正确创建
然后我得到了我的api谁得到调用和解码它。在我用来解码和获取参数的函数中:
$descripcion_cool = str_replace("%"," ",$_GET['descripcion']);
echo utf8_decode($descripcion_cool);
$query = 'INSERT INTO `Categorias`(`idCamping`, `idCategoria`, `descripcion`) VALUES (
"'.mysql_real_escape_string($_GET['id']).'",
"'.mysql_real_escape_string($_GET['idCategoria']).'",
"'.mysql_real_escape_string($descripcion_cool).'")';
这将输出以下内容:
test new?tegoryINSERT INTO `Categorias`(`idCamping`, `idCategoria`, `descripcion`) VALUES (
"9999",
"3",
"test new�tegory")null
如您所见,php向url参数添加了一些特殊字符。我在干什么?谢谢
PD:在我的php文件中,我尝试添加:
header('Content-type: text/plain; charset=utf-8');
但它一直在做同样的事情
提前感谢假设您发送的参数值带有空格,那么您将通过将空格替换为
%
对其进行编码。事实上,你不必那么做。如果您想对传递的参数/查询进行编码,可以使用encodeURIComponent()
方法。如果要对url进行编码,请使用encodeURI()
这将安全地对url进行编码。始终
encodeURIComponent
查询字符串参数。或者让jQuery为您这样做。如果我错了,请纠正我,但是$\u GET['var']
变量是否已经返回了一个转义字符串?您必须转义它,以便$\u GET
可以正确地取消转义。他正确地转义了它,但在$\u GET返回后又解码了两次。..OP正在做两个错误:)不encodeURIComponent
应应用于URI组件(例如查询字符串名称/值),而不是URI本身。
description = encodeURIComponent(description);
var url = 'http://myapi/OfertasVentaOnline/api.php?method=update&function=categoria&id='+id+'&idCategoria='+id_categoria+'&descripcion='+descripcion+'&format=json';
$.getJSON(url, function (data){
});