开发者

JQuery ajax - is it possible to return two different sets of data on success?

Using this ajax request I am returning a view fragment of populated html to insert into a particular div within the layout.

my question is how do I declare #theDiv, I have the id available at the point where the view fragment is constructed (within the view_Controller).

Ideally I would return some json at the same time for instance, specifying:#theDiv, and any other parameters such as which nav bar element should be active etc....

    $.ajax({
      type: "POST",
      url: "controller/view_Controller.php",
      data: dataStrin开发者_如何学JAVAg,
      cache: false,
      dataType: "html",
      success: function(html){

           $('#theDiv').html(html)

        };
        });


You need to build an array of information on the backend:

$data = array (
    'html' => $html,
    'target' => '#myDiv'
);

header('Content-type: application/json');
echo json_encode($data);

And in your JS:

$.ajax({
    type: "POST",
    url: "controller/view_Controller.php",
    data: dataString,
    cache: false,
    dataType: "json",
    success: function(data){
       $(data.target).html(data.html)
    };
});

I don't quite understand what you mean by specifying success and error -- do you mean you want your script to be able to define the Javascript to be called on success?


Try this instead:

$.ajax({
          type: "POST",
          url: "controller/view_Controller.php",
          data: dataString,
          cache: false,
          dataType: 'json',
          success: function(data){

               $(data.id).html(data.html)

         };
});

Have the script pass back a JSON object with the id attribute set to the id of the element, and have the html element set to the HTML string that you want it set with.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜