Ajax传地址URL编码格式

时间:2021-05-04 00:19:54

当我们用Ajax传递路径的时候,有可能会出错,尤其是路径中有汉字的时候,传递的路径与接收的路径不同。解决方法:在传递路径的时候对路径编码,接收的时候解码存入数据库。

如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="../jquery-1.11.2.min.js"></script>
</head> <body>
<img src="img/果子.jpg" id="tupian" /><br />
</body>
</html>
<script type="text/javascript">
$(document).ready(function(e) { var url = $("#tupian").attr("src");
var lujing = encodeURIComponent(url); //URL编码
//alert(lujing);
$.ajax({
url:"chuli.php",
data:{url:lujing},
type:"POST",
dataType:"TEXT",
success: function(data){
//alert(data);
if(data.trim()=="OK")
{
alert("添加成功!");
}
else
{
alert("添加失败!");
}
}
});
});
</script>

处理页面chuli.php:

<?php
$url = $_POST["url"];
$lujing = urldecode($url); //URL解码
include("../DB.class.php");
$db = new DB();
$sql = "insert into nation values('n014','{$lujing}')";
if($db->Query($sql,1))
{
echo "OK";
}
else
{
echo "NO";
}