Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

php - jQuery Ajax return html AND json data

I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.

What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.

This is what I'm doing now:

     $.ajax({
    type: "POST",
    url: "inc/"+page+".php",
    data: "id="+encodeURIComponent(pageID),
    success: function(html){

        $("body > .container").html(html);

      }
      });

This is what I'd like to be able to do:

     $.ajax({
    type: "POST",
    url: "inc/"+page+".php",
    data: "id="+encodeURIComponent(pageID),
    success: function(html){
        $("body > .container").html(html);
            $("title").html(json.PageTitle)
      }
      });

on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

HTML and data wrapped in JSON

You can do it by returning a 2 element JSON array. The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.

Serverside

$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);

Clientside

//Ajax success function...

success: function(serverResponse){
    $("body > .container").html(serverResponse.html);
    var data = JSON.parse(serverResponse.data);
    $("title").html(data.page_title)
  }

Note 1: I think this is what @hakre meant in his comment on your question.

Note 2: This method works, but I would agree with @jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...