当$ .post没有时,jQuery $ .ajax工作

nip*_*ese 2 jquery post json

我只是想做一个简单的$ .post调用.

<body>
<div id="main">
    <div id="diver">
    </div>
    <form id="entry_field_container" action="" method="post" accept-charset="utf-8">
        <input type="text" name="entry_field" value="" id="entry_field">

        <input id="send" type="submit" value="send">
    </form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('#send').click(function(e){
            e.preventDefault();
            var txt = $('#entry_field').val();
            $.post(
                'http://localhost/proc.php',
                {
                    name:'me',
                    text:txt
                },
                function(data){
                    console.log(data);
                    $('#diver').html(data)
                },
                'json'
            )

        })
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在proc.php里面:

<?php
    $name = $_POST['name'];
    $text = $_POST['text'];
    echo "{\"" . $name . "\", \"" . $text . "\"}";
?>
Run Code Online (Sandbox Code Playgroud)

由于某种原因,POST返回200,但控制台永远不会回来data,它只是空白.

我最难理解的是为什么这个$ .ajax函数每次都有效.这不仅仅是同一事物的更详细的例子吗?

$.ajax({
    'type':    'POST',
    'url':     'http://localhost/proc.php',
    'async':   true,
    'cache':   false,
    'global':  false,
    'data':    {
       'name':'me',
        'text':txt
    },
    'error': function(xhr,status,err){
        alert("DEBUG: status"+status+" \nError:"+err);
    },  
    'success': function(data){
        console.log(data);
    }   
});
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 5

在你的$.post你告诉jQuery的返回的文本是JSON,但在你的$.ajax你不是.

$.post失败,因为从PHP返回的文本是不是有效的JSON.

{"me", "test"}
Run Code Online (Sandbox Code Playgroud)

这不是有效的JSON. {}是一个对象,所以它需要键:

{"name": "me", "text": "test"}
Run Code Online (Sandbox Code Playgroud)

或者,也许你想要一个array([]):

["me", "test"]
Run Code Online (Sandbox Code Playgroud)

PS在PHP中创建JSON时,强烈建议您使用json_encode而不是自己制作JSON.


Del*_*man 5

你在$ .post调用上指定了一个"json"格式,但是没有在$ .ajax调用上,可能是你没有返回一个有效的JSON响应,这就是为什么你的$ .post没有执行它的成功方法?