jquery $ .post函数的结果数据

时间:2009-10-13 18:20:59

标签: jquery ajax json post

当我进行ajax调用时(参见下面的代码),什么是“数据”。如何设置和获取数据

//  $.post()  
 $("#post").click(function(){  
     $("#result").html(ajax_load);  
     $.post(  
         loadUrl,  
         {language: "php", version: 5},  
         function(data){  
             $("#result").html(data);  
         },  
         "json"  
     );  
 });

4 个答案:

答案 0 :(得分:5)

数据是输入的序列化值。例如:

<form>
    <input type='text' name='myText1' value='hello'/>
    <input type='text' name='myText2' value='world'/>
</form>

你现在可以运行:

var myData = $('form').serialize();
alert(myData);

你的消息框会说:

myText1=hello&myText2=world

myData 是您要传递到$ .post函数的数据值。

由于您不熟悉jQuery,我建议您尝试使用$.ajax函数。它有很多选择,但我一直认为它比$ .post更直接,更容易理解。以下是我如何使用它:

$.ajax({
    type: "POST",    //define the type of ajax call (POST, GET, etc)
    url: "my-ajax-script.php",   //The name of the script you are calling
    data: myData,    //Your data you are sending to the script
    success: function(msg){
        $("#result").html(msg);   //Your resulting action
    }
});

顺便说一下,不要忘记,为了使用jQuery serialize函数,所有输入都需要设置 name 属性,否则serialize函数会忽略它们。

答案 1 :(得分:1)

documentation for $.post表示数据“可以是xmlDoc,jsonObj,html,text等......”。这是服务器为您使用给定参数指定的loadUrl返回的任何内容(在您的情况下,语言:“php”,版本:5),因此您需要检查服务器返回的内容。

只需在回调中提醒(数据),您就会看到返回的内容。

更新:将'responseText重命名为'数据',因为OP更改了问题。

答案 2 :(得分:0)

例如,我使用:

$(document).ready(function(){
$("#btSend").click(function() {
    $.post("/Ajax/script.php", {nome: $("#nome").val(), email: $("#email").val()}, function(data) {
        alert(data);
    });
    return false;
});

});

script.php返回我想要显示的内容,但您可以更改为使用'data'进行其他操作。 'btSend'是一个图像,'nome'和'email'是html文本框。

这有效:)

答案 3 :(得分:0)

$.post('fileName.php',{

data: $('#id').val(),
},
function(response)
{
  alert(response);
}
}