Jquery | 如何将变量添加到Ajax的URL中?

3

我不确定如何做到这一点,我的变量是:

var username = "test";
var username = "1234";

我希望在URL请求中包含这两个变量。
$.ajax({
    url: "http://myurl.com/index.php?username=(+username+)&password=(+password+)",

学习如何连接字符串。 - StackSlave
4个回答

3
"http://myurl.com/index.php?username="+ username +"&password="+ password

将变量放在字符串外部进行拼接。

你能帮我检查一下我的 jsfiddle 吗?http://jsfiddle.net/3Lqsx/7447/ 它没有获取到变量。 - cinassa
同时对用户名和密码进行编码 encodeURIComponent(username);这可以减轻一些注入攻击。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent - Chris C.
将您的用户名和密码声明在.each函数之外,这样它们就可以在ajax函数中使用。 - Chris C.
关于变量作用域的更多信息,请参考这里:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope - Chris C.
谢谢Chris,我做到了,它可以工作。但现在它开始出现其他循环问题,请求被发送两次。https://stackoverflow.com/questions/50617330/how-to-arrange-the-next-ajax - cinassa

2

试着使用ES6模板字面量,像这样是最好的方式:

url:`http://myurl.com/index.phpusername=${username}&password=${password}`,

2

你可以简单地使用ES6中的一个特性,叫做模板字符串。模板字符串用反引号(` `)包裹,而不是双引号或单引号。模板字符串可以包含占位符,这些占位符由美元符号和花括号(${expression})表示。

var username = "test";

var password = "1234";

var url = `http://myurl.com/index.php?username=${username}&password=${password}`;
console.log(url);

所以你的代码看起来像这样:
var username = "test";
var username = "1234";
$.ajax({
    url: `http://myurl.com/index.php?username=${username}&password=${password}`,

在第18行的“var username和password”之后,返回已翻译的文本。 - cinassa

2

你好,请查看下面的答案:

var username = "test";
var username = "1234";
$.ajax({ url: "http://myurl.com/index.php?username="+username+"&password="+password+"});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接