将文本参数传递给jQuery上.load函数的url变量

时间:2012-10-09 14:45:17

标签: javascript jquery text parameters load

我试图通过参数(带空格)将文本传递给加载函数,但它似乎不起作用。

目前我这样做:

var text ="hello world this is an example";
$("#selector").load("http://"+ document.domain + "/myfunction/"+text);

有什么办法吗?

如果我直接通过URL调用该函数,而不是使用jQuery,则效果很好。

感谢。

2 个答案:

答案 0 :(得分:4)

您应该使用encodeURI编码“text”:

var text = encodeURI('hello world this is an example');

这将确保您的空格被替换为url兼容字符,当您直接访问该网址时,您的浏览器会在内部执行这些字符。

答案 1 :(得分:1)

直接通过URL调用该功能可能在您的浏览器中运行良好。但这不是未来的证据。您必须使用encodeURI函数对网址进行编码。添加用户给定的数据后。

var text ="hello world this is an example",
url = encodeURI("http://"+ document.domain + "/myfunction/"+ text);
$("#selector").load(url);

在服务器端,你可以做这样的事情来取回用户输入的数据。

$data = urldecode($_SERVER['REQUEST_URI']);
// This will return
// /myfunction/hello world this is an example
相关问题