简体   繁体   中英

jQuery: refresh div content on button click, from a php file

Fiddle: http://jsfiddle.net/feqnLs6o/

I am trying to refresh <div id="refreshableDiv"> on button1 click, using jQuery. I want to load the content of http://shiro-desu.com/scr/test/test.php to the <div> every time the button1 is clicked. As i haven't used jQuery before, i fail to understand why the following doesn't reload the content of div.

script code:

$(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 code:

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

Any ideas?

http://jsfiddle.net/feqnLs6o/

Just change your html code of button to:

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

You are using id when binding click event.

Seeing as you're not posting any data - it would make more sense to do an AJAX GET Request instead.

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

Inspecting console log for the request shows the following error:

XMLHttpRequest cannot load http://shiro-desu.com/scr/test/test.php . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://fiddle.jshell.net ' is therefore not allowed access. fiddle.jshell.net/_display/:1

Putting:

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

At the top of http://shiro-desu.com/scr/test/test.php should solve that issue.

It's in regards to http://en.wikipedia.org/wiki/Same-origin_policy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM