$ .ajax jquery中的数组,然后将其发送到php页面

时间:2011-05-12 07:12:44

标签: php jquery ajax post

jQuery(document).ready(function(){
    // Set the data text  
    var dataText = "
    { 
        name: 'John',
        time: '2pm' 
     }";  

    alert(dataText);
    // Create the AJAX request  
    $.ajax({  
        type: "POST",                    // Using the POST method  
        url: "/ajax/analytics/push",      // The file to call  
        data: dataText,                  // Our data to pass  
        success: function() {            // What to do on success  
             alert("Data Loaded: " + dataText);
        }  
    });  
});  
</script>   

你好我还在学习ajax。我们如何推送$ _POST数组?

1.im尝试做类似

的事情
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';

然后以某种方式将其变成

$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';

然后将其发送到网址..

2.有没有办法调试这个?我现在正在做的是写作

        # somehow doesnt work becouse its not auto refresh when the ajax sends a post
    var_dump($_POST);

        # ok heres how i debug it right now.
    ob_start();
    // write content
    $content = $_POST;
    ob_end_clean();
    file_put_contents('CACHE',$content);

进入文件,我希望有更好的解决方案..

谢谢你的关注。 Adam Ramadhan

3 个答案:

答案 0 :(得分:2)

我不完全确定你在做什么。您似乎手动构建JSON(并且没有正确执行),然后将其(以JSON序列化的字符串形式)传递给您的文件。然后,您似乎希望PHP自动解析它。

将它作为键值对发送会更好。如果你传入一个对象,你可以让jQuery为你做这件事。这与您现有的代码没什么不同:

var dataText = 
{ 
    name: 'John',
    time: '2pm' 
};  

请注意,我已删除双引号。这主要是因为在没有转义换行符的情况下使JS字符串覆盖多行是非法的。这也是因为您希望对象传递到$.ajax来电。

这些应该现在可以$_POST['name']$_POST['time']使用。

答案 1 :(得分:0)

file_put_contents('CACHE',serialize($content));

foreach($_POST as $k => $v) $content .= $k .'='.$v;

答案 2 :(得分:0)


jQuery(document).ready(function(){
    // Set the data text  
    var dataText = 
    { 
        name: 'John',
        time: '2pm' 
     };  

    alert(dataText);
    // Create the AJAX request  
    $.ajax({  
        type: "POST",                    // Using the POST method  
        url: "/ajax/analytics/push",      // The file to call  
        data: dataText,                  // Our data to pass  
        success: function() {            // What to do on success  
             alert("Data Loaded: " + dataText);
        }  
    });  
});  
 


        # ok heres how i debug it right now.
    ob_start();

     # somehow doesnt work becouse its not auto refresh when the ajax sends a post
    var_dump($_POST);
    $content = ob_get_contents();
    ob_end_clean();
    file_put_contents('CACHE',$content);