【问题标题】:jQuery: refresh div content on button click, from a php filejQuery:在按钮单击时刷新 div 内容,来自 php 文件
【发布时间】:2014-10-04 16:58:51
【问题描述】:

小提琴:http://jsfiddle.net/feqnLs6o/

我正在尝试使用 jQuery 在点击 button1 时刷新 <div id="refreshableDiv">。 每次单击button1 时,我都想将http://shiro-desu.com/scr/test/test.php 的内容加载到<div>。 由于我之前没有使用过jQuery,所以我无法理解为什么以下内容不会重新加载div的内容。

脚本代码:

$(document).ready(function(){
 $('#button1').click(function(){
        $.post(
        "http://shiro-desu.com/scr/test/test.php",
        {
        },
        function(data){
        $('#refreshableDiv').html(data);
        });
    });
});

test.php

<?php echo "543"; ?>

html代码:

<div id="refreshableDiv">Primary content</div>
<input type="submit" class="button1" name="button1" value="Reload"/>

有什么想法吗?

http://jsfiddle.net/feqnLs6o/

【问题讨论】:

  • 您正在使用 id-selector(#button1) 但按钮没有 id。此外,您正在尝试发出跨域 ajax 请求(同源策略)..您需要为此启用 CORS...
  • @ArunPJohny 我添加了 id="button1" jsfiddle.net/feqnLs6o/3 ,但它不起作用,我不知道 CORS 是什么,你能不能编辑这个小提琴以便它工作?如果可能的话,因为它只有 5 行代码
  • CORS(Same Origin Policy) 必须在服务器端启用...对于 PHP see this
  • @ArunPJohny 这应该放在我的test.php 文件中吗? &lt;?php header("Access-Control-Allow-Origin: *");
  • @ArunPJohny 感谢您的回复,问题是它在 jsfiddle 上运行,我现在明白您的意思了,非常感谢,id="button1" 也是问题所在,它在我的服务器上运行良好

标签: javascript php jquery html


【解决方案1】:

只需将按钮的 html 代码更改为:

<input type="submit" id="button1" name="button1" value="Reload"/>

你在绑定点击事件时使用了id。

【讨论】:

  • 这只是因为您正在发出跨域 Ajax 请求。如果您想在小提琴中进行测试,只需将 URL 更改为 /echo/html 并在数据参数中传递 html 数据,例如 {html:'

    test

    '}
【解决方案2】:

鉴于您没有发布任何数据 - 改为执行 AJAX GET 请求会更有意义。

$(document).ready(function(){
 $('.button1').click(function(){
     $.ajax({
         url:'http://shiro-desu.com/scr/test/test.php'
     }).done(function(response) {
        $('#refreshableDiv').html(response); 
     });
 });
});

检查请求的控制台日志显示以下错误:

XMLHttpRequest 无法加载 http://shiro-desu.com/scr/test/test.php。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://fiddle.jshell.net” 使用权。 fiddle.jshell.net/_display/:1

推杆:

<?php header('Access-Control-Allow-Origin: *'); ?>

http://shiro-desu.com/scr/test/test.php 的顶部应该可以解决这个问题。

关于http://en.wikipedia.org/wiki/Same-origin_policy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2014-07-11
    • 2012-01-31
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多