开发者

Callback from load with jQuery?

开发者 https://www.devze.com 2023-02-07 04:43 出处:网络
I use PHP开发者_StackOverflow中文版 and jQuery and here is my code (that works so far). $(\".design\").load(\"<?php echo get_bloginfo(\'url\'); ?>/?addmod_ajax=1\",{

I use PHP开发者_StackOverflow中文版 and jQuery and here is my code (that works so far).

$(".design").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{
    menu: 'layout',
});

This is what I want to do.

If the PHP-file I'm calling find some values in a PHP array (on the server side), I want the jQuery to append (add) some content to the HTML element. Is it possible to make callbacks like that?

It's important to me that I can still send my POST variables to my PHP file.


You can generate markup and add it to your page with load() function you already have. I'm going to assume that you are returning JSON from your ajax method:

$(".design").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{
    menu: 'layout' }, function(data) { 
 var markup = '<ul>';
 for (var x = 0; x < data.length; x++ ) {
markup += '<li><a href="' + data[x].Url + '">'+data[x].Text+'</a></li>';
 }
 markup += '</ul>';
 #('menu').html(markup); });

The load() function accepts as an optional third argument a function that will work with the response of your ajax call. In this instance for illustrative purposes I'm assuming you want to build some navigation, so I'm iterating through an array and building an unordered list as I go.

Its possible to have even more control / options with your ajax requests as well. I recommend you have a look at the the .ajax() for an idea of the things you can do.

It is an older topic, but there is a discussion here on stack overflow that shows various ways you could generate html and insert it into the DOM: JQuery: Build HTML in 'memory' rather than DOM. There is also the tmpl() plugin that is very useful for generating markup. You can learn more about tmpl() here.


As @yoda said in a comment you can use $.ajax() to acomplish this as shown below:

 $.ajax({
   type: "GET",
   url: "<?php echo get_bloginfo('url'); ?>",
   data: "addmod_ajax=1",
   success: function(data){
     alert("data is " + data );
   }
 });

you can swap type for POST if you need to

0

精彩评论

暂无评论...
验证码 换一张
取 消