javascript 以 HTML 格式显示 Ajax 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20890083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:33:46  来源:igfitidea点击:

Display Ajax response in HTML

javascriptphpjqueryajax

提问by user2570937

I'm calling a PHP file, and it's returning the response when I view it in Firebug. However, it's not displaying on my page. I'm not sure if the success is actually firing, because I can't even run an alert, but it is working because the PHP code is firing and returning what it's supposed to.

我正在调用一个 PHP 文件,当我在 Firebug 中查看它时它会返回响应。但是,它没有显示在我的页面上。我不确定成功是否真的触发了,因为我什至无法运行警报,但它正在工作,因为 PHP 代码正在触发并返回它应该做的。

<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>

<script>
    $.ajax({
        type: "GET",
        url: 'https://www.example.com',
        dataType: 'jsonp',
        contentType: "text/html",
        crossDomain:'true',
        success: function (data) {
            $(".result").html(data);
        }
    });
</script>

<div class="result"></div>

回答by Kevin Seifert

You need to make the ajax call on load or document ready. The div may not exist at the time of response (page is interpreted top down).

您需要在加载或文档准备好时进行 ajax 调用。响应时 div 可能不存在(页面自上而下解释)。

回答by Neta Meta

Just a little lesson about what your are doing.

只是关于你在做什么的一点教训。

When working with any form of Ajax (or JavaScript in general), it is usually imperative to have your console open. You will be able to see your request, your response, and whole other useful information.

使用任何形式的 Ajax(或一般的 JavaScript)时,通常必须打开控制台。您将能够看到您的请求、您的回复以及所有其他有用的信息。

I usually work with Firefox and Chrome from time to time.

我通常不时使用 Firefox 和 Chrome。

You can open your console by right clicking on the page anywhere and inspect an element with Firebug (on Firefox).

您可以通过右键单击页面的任意位置来打开控制台,并使用 Firebug(在 Firefox 上)检查元素。

And inspect element in Chrome.

并在 Chrome 中检查元素。

Once you see the Ajax call, click the +and see its content.

看到 Ajax 调用后,单击+并查看其内容。

You should see something like:

你应该看到类似的东西:

Headers Post Response JSON Cookies or something alike.

Headers Post Response JSON Cookies 或类似的东西。

I hope that helps.

我希望这有帮助。