Ajax 将数据传递给 php 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6782230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax passing data to php script
提问by NeedHelp
I am trying to send data to my PHP script to handle some stuff and generate some items.
我正在尝试将数据发送到我的 PHP 脚本以处理一些内容并生成一些项目。
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname
is I get nothing, I try to get the album name by $albumname = $_GET['album'];
在我的 PHP 文件中,我尝试检索专辑名称。虽然当我验证它时,我创建了一个警报来显示albumname
我什么也没得到,但我尝试通过以下方式获取专辑名称$albumname = $_GET['album'];
Though it will say undefined :/
虽然它会说未定义:/
回答by Darin Dimitrov
You are sending a POST AJAX request so use $albumname = $_POST['album'];
on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
您正在发送 POST AJAX 请求,因此请$albumname = $_POST['album'];
在您的服务器上使用它来获取值。另外,我建议您像这样编写请求以确保正确编码:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
或其较短的形式:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
如果您想使用 GET 请求:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
或其较短的形式:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];
. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false
setting.
现在您可以在您的服务器上使用$albumname = $_GET['album'];
. 小心使用 AJAX GET 请求,因为它们可能会被某些浏览器缓存。为了避免缓存它们,您可以设置cache: false
设置。
回答by rcravens
Try sending the data like this:
尝试发送这样的数据:
var data = {};
data.album = this.title;
Then you can access it like
然后你可以像这样访问它
$_POST['album']
Notice not a 'GET'
注意不是“GET”
回答by kaushik
You can also use bellow code for pass data using ajax.
您还可以使用波纹管代码使用 ajax 传递数据。
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});