我可以在jquery $ ajax中获取更多变量而不是字符串吗? [英] Can i get more variables instead of string in jquery $ajax?

查看:101
本文介绍了我可以在jquery $ ajax中获取更多变量而不是字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本:

$.ajax({    
    url: 'submit_to_db.php',
    type: 'POST',
    data: 'name=' + name + '&email=' + email + '&comments=' + comments,

success: function(result) {
    $('#response').remove();
    $('#container').append('<p id="response">' + result + '</p>');
    $('#loading').fadeOut(500, function() {
    $(this).remove();
});

}
});

然后在我的php文件中,插入数据库后,我回显"commentupdated",然后附加到我的容器中并逐渐消失.同时,我也想将新注释插入容器中.所以我试了echo评论更新!& com =".$ comment;但它以字符串而不是2个变量的形式返回. \

Then in my php file, after insert to database, I echo "comment updated", then append to my container and slowly fade away. In the meantime, I want to insert the new comment into the container as well. So I tried echo "comment updated!&com=".$comment; but it was returned as string rather than 2 variables. \

太奇怪了,我在我的php文件中变得未定义

So weird, i am getting undefined in my php file,

$ comment = $ _POST ['comment']

$comment = $_POST['comment']

我的js或php代码有问题吗?

is there something wrong in my js or php code?

推荐答案

响应不包含变量.它包含文本,即您发出的请求的结果. 我建议使用JSON.

The response doesn't contain variables. It contains text, the result of the request you made. I recommend using JSON.

#in submit_to_db.php
$response = array();

if($submitted) { #if the comment was inserted successfully
  $response['status'] = 'OK';
  $response['message'] = 'Your comment was added';
  $response['comment'] = $_POST['comments'];
}
else {
  $response['status'] = 'ERROR';
  $response['error'] = 'You must enter your name'; #just an example
}
echo json_encode($response);
#would yield {"status":"OK","comment":"the comment just added"}


#in yourJsFile.js
$.ajax({    
    url: 'submit_to_db.php',
    type: 'POST',
    data: 'name=' + name + '&email=' + email + '&comments=' + comments,
    dataType: 'json',
    success: function(response) {

        if(response.status == 'OK') {
           $('#response').remove();
           $('#container').append('<p id="response">' + response.message + '</p>');
           $('#loading').fadeOut(500, function() {
             $(this).remove();
           });

           $('#comments').append('<li>' + response.comment + '</li>'); //just an example
        }
        else {
           $('#container').append('<p id="response">' + response.error + '</p>');
        }
    }
});

更多 信息.

这篇关于我可以在jquery $ ajax中获取更多变量而不是字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆