0

我正在尝试使用 jquery 进行 ajax 调用,它似乎正在工作,但我无法让它填充结果 div。

继承人的JS代码:

            <script> 
                $(document).ready(function(){
                    $(document).on('change', '#flip-1', function(){    
                        var datastring = $("#some-form").serialize();
                        $.ajax
                        ({
                            type: "POST",
                            url: "test.php",
                            data:  datastring,
                            dataType: 'html',
                            complete: function(data) {
                                $('#results').html (data);
                                }
                            });
                        });
                    });
            </script>
            <form id="some-form">
                <label for="flip-1">Flip toggle switch:</label>
                <select id="flip-1" name="flip-1" data-role="flipswitch">
                    <option value="off">Off</option>
                    <option value="on">On</option>
                </select>
            </form>

<div id="results">Loading users...</div>

这是PHP代码:

<?php

if ($_POST['flip-1'] == 'on') {
    echo 'oh is on!';
} elseif ($_POST['flip-1'] == 'off') {
    echo 'no, its not on';
}
?>      

这就是 chrome “检查元素”调试器对标头所说的内容:

Request URL:http://localhost/smart_home/test.php
Request Method:POST
Status Code:200 OK

Request Headers
POST /smart_home/test.php HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 9
Accept: text/html, */*; q=0.01
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/smart_home/index.php
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4

Form Data
flip-1=on

Response Headers
HTTP/1.1 200 OK
Date: Thu, 27 Feb 2014 20:58:08 GMT
Server: Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6
X-Powered-By: PHP/5.5.6
Content-Length: 20
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html

这就是响应选项卡所说的:当按钮变为打开位置时:

oh is on!      

当更改为“关闭”时

no, its not on      

有人有什么想法吗?

谢谢!

4

1 回答 1

1

complete回调不直接接收响应数据(第一个参数是一个对象jqXHR)。success使用or.done()回调通常更简单:

$.ajax({
    type: "POST",
    url: "test.php",
    data: datastring,
    dataType: 'html',
    success: function (data) {
        $('#results').html(data);
    }
});

或者

$.ajax({
    type: "POST",
    url: "test.php",
    data: datastring,
    dataType: 'html'
}).done(function (data) {
    $('#results').html(data);
});

http://api.jquery.com/jQuery.ajax/

于 2014-02-27T21:28:17.660 回答