所以这是我的问题,我使用AJAX(jQuery)发布一个表单,process.php但页面实际上需要回应一个响应,如apple或plum.我不确定如何从响应中获取process.php并将其存储为变量...
这是我到目前为止的代码:
<script type="text/javascript">
function returnwasset(){
alert('return sent');
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(){
//echo what the server sent back...
}
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
我还需要process.php在json中回应响应吗?或者纯文本会好吗?
很抱歉,如果这听起来像一个愚蠢的问题,这是我第一次在Ajax中做这样的事情.
PS:我如何在上面的代码中命名POST请求?
Mar*_*c B 41
<?php echo 'apple'; ?> 几乎就是你在服务器上所需的一切.
至于JS方面,服务器端脚本的输出作为参数传递给成功处理函数,所以你有
success: function(data) {
alert(data); // apple
}
Run Code Online (Sandbox Code Playgroud)
小智 27
好的做法是使用这样的:
$.ajax({
type: "POST",
url: "/ajax/request.html",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
console.log(response.blablabla);
// put on console what server sent back...
}
});
Run Code Online (Sandbox Code Playgroud)
和php部分是:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo json_encode(array("blablabla"=>$variable));
}
?>
Run Code Online (Sandbox Code Playgroud)
Eth*_*han 15
<script type="text/javascript">
function returnwasset(){
alert('return sent');
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
dataType:'text'; //or HTML, JSON, etc.
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
Tuc*_*ker 10
在您的PHP文件中,当您回显数据时使用json_encode(http://php.net/manual/en/function.json-encode.php)
例如
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
Run Code Online (Sandbox Code Playgroud)
在您的javascript代码中,当您的ajax完成时,json编码的响应数据可以转换为js数组,如下所示:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
185006 次 |
| 最近记录: |