Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...