4

我似乎无法从中获得回调,但它得到了响应,这是一个简单的测试。任何人都知道为什么它不按我的意愿做

<script type="text/javascript">
$(document).ready(function(e) {
    $("button").click(function() {
        var msg = $("#txt").val();
        $.post(
            "http://localhost/bot.php",
            {msg: msg},
            function(data,status) {
                $("p").text(data);
            }
        );
    });
});
</script>

PHP,任何人都可以推荐一个好的 JavaScript 工具来帮助我查找错误吗?

<?php

class ai
{
    private $msg;

    public function __construct($msg)
    {
        $this->msg = $msg;
    }

    public function respond()
    {
        switch($this->msg)
        {
            case "hi":
                echo "Hello Mr Brown How are You";
                break;
            case "fine":
                echo "Good to hear Did you know Zanda hard Coded me?";
                break;
            case "im fine":
                echo "Good to hear Did you know Zanda hard Coded me?";
                break;
            default:
                echo "??????????????????????????????" .
                     "That means i was extra rush prototype.......i cant answer that";
        }
    }
}

$talk = new ai($_POST['msg']);
$talk->respond();

?>


<div class="box">
<p>text</p>
<textarea id="txt"></textarea>
<button>click</button>
</div>

有 html 使它尽可能短

4

2 回答 2

1

在这里也可以尝试更改您的$.postfor$.ajax以便您可以指定错误回调。$.get$.post只是$.ajax无论如何的简写。尝试这样的事情:

("button").click(function() {
    var msg = $("#txt").val();
    $.ajax(
        url: "http://localhost/bot.php",
        data: {msg: msg},
        dataType: 'jsonp',
        success: function(data,status) {
            console.log(data, "returned with status:", status);
        },
        error: function(obj, status, error){
            console.log("Error!", obj, status, error);
        }
    );
});

仅仅因为您收到200回复并不意味着一切正常。这就是说 POST 是成功的。您需要检查响应文本以查看是否返回任何错误。

编辑:添加dataType: 'jsonp'到请求中。

于 2013-08-13T10:38:54.287 回答
0

It seems like it is due to the Same Origin Policy and from the MDN documentation

The port number is kept separately by the browser. Any call to the setter, including document.domain = document.domain causes the port number to be overwritten with null. Therefore one can not make company.com:8080 talk to company.com by only setting document.domain = "company.com" in the first. It has to be set in both so that port numbers are both null.

So that is the reason you are getting null as you said in your responses

Try adding datatype:"jsonp". It shoudl work like this.

$(document).ready(function(e) {
    $("button").click(function() {
        var msg = $("#txt").val();
        $.post(
            "http://localhost/bot.php",
            {msg: msg},
            function(data,status) {
                $("p").text(data);
            },
            dataType:"jsonp"
        );
    });
});

Further reading here.

Hope that helps.

于 2013-08-13T10:37:37.253 回答