Dan*_*han 9 javascript php ajax jquery
这是我在index.html上的代码:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'test.php',
data: "check",
success: function(data){
alert(data);
}
});
</script>
</head>
<body>
<div></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如何编写test.php以获取在AJAX API中发送的"数据"?
你可以这样试试
$.ajax({
type: "POST",
url: 'test.php',
data: {"data":"check"},
success: function(data){
alert(data);//This will alert Success which is sent as the response to the ajax from the server
}
});
Run Code Online (Sandbox Code Playgroud)
并在test.php
if(isset($_POST['data']) && $_POST['data'] == 'check'){
//$_POST['data'] contain the value that you sent via ajax
//Do something
echo 'Success';
}
Run Code Online (Sandbox Code Playgroud)
你可以 查看更多
如果你想用jquery ajax处理更多的数据.我更喜欢json数据类型.
$.ajax({
type: "POST",
url: 'test.php',
dataType: 'json',
data: {"data":"check"},
success: function(data){
alert(data.value1);
alert(data.value2);
}
});
Run Code Online (Sandbox Code Playgroud)
if(isset($_POST['data']) && $_POST['data'] == 'check'){
//Data 1
$data['value1'] = 'Data 1 Got Successfully';
//Data 2
$data['value2'] = 'Data 2 Got Successfully';
$resonse = json_encode($data);
echo $response;
}
Run Code Online (Sandbox Code Playgroud)
您在这里问一个非常基本的问题。您首先应该阅读一些Ajax教程。只是为了帮助您(假设您知道发送数据的GET和POST方法),数据中的“数据”:函数(数据)中的“检查”与“数据”不同。为了清楚起见,您应为它们起个不同的命名,如下所示:
$.ajax({
type: "POST",
url: 'test.php',
data: "check",
success: function(response){
alert(response);
}
});
Run Code Online (Sandbox Code Playgroud)
这清楚地表明,一个是要通过POST参数发送到test.php文件的数据,另一个是运行后从test.php文件获得的响应。实际上,POST到test.php的数据参数必须像这里这样是一个哈希值(我在这里假设键为“类型”:
$.ajax({
type: "POST",
url: 'test.php',
data: {"type":"check"},
success: function(response){
alert(response);
}
});
Run Code Online (Sandbox Code Playgroud)
显然,数据中可以有更多的键-值对。
因此,假设您的test.php文件是这样的:
if(isset($_POST['type'])){
//Do something
echo "The type you posted is ".$_POST['type'];
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您的警报应显示为:“您发布的类型为check”。这将根据您在AJAX调用中为“类型”键发送的值而改变。
| 归档时间: |
|
| 查看次数: |
53051 次 |
| 最近记录: |