div 未被 ajax 请求填充



我正在尝试使用 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      

有人有什么想法吗?

谢谢!

complete

调不直接接收响应数据(第一个参数是 jqXHR 对象)。通常,使用 success.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/

相关内容

  • 没有找到相关文章

最新更新