-2

I'm completely confused with the data transferred by a jQuery-AJAX (specifically I've been using $.post mostly)

I've had a few attempts at transferring data to/from a PHP page and I'm left unsure what to use when, and how.

I've seen it done in a bunch of ways:

var dataString = 'username='+ username + '&userpassword=' + password;   

var dataString = '<?php echo $someVariable ?>';

I've seen it done with serialize(), json_encode, stringify, sometimes nothing at all. I find this very confusing, how do I know which to use, when and how? And most importantly, what tutorial/guide can I read to understand this thoroughly?

4

2 回答 2

3

只需使用:

$.post(url, {
    username: ...,
    password: ...
});

然后在您的 PHP 中,这些字段将显示为$_POST['username']等。

唯一变得更复杂的情况是,如果您希望为同一个键发送多个值(在x-www-url-formencoded语法中未标准化),或者您要发送的值本身是对象或值数组。在后一种情况下,将(但不是整个表单数据)转换为 JSON,并在 PHP 中对其进行解码是有意义的。

于 2013-05-22T14:23:35.740 回答
0

你可以尝试这样的事情:

$.ajax({
            url:url,
            dataType: 'json',
            type:'POST',
            data:{username:youusernamevalue,password:yourpasswordvalue}, 
            success:function(data){
                //do something
            },
            error:function(){
             do something 
            }
        });
于 2013-05-22T15:07:15.760 回答