jQuery Ajax返回html和json数据
我不确定是否有任何方法可以做到这一点,但如果有一个简单的解决方案,这将解决我的许多问题。
我需要/希望能够做的是在我成功的ajax请求中返回HTML和JSON。 原因是,我想请求一个文件并返回所有该页面,但我也希望能够从json中的页面返回一组指定的信息,所以我可以将它用于其他事情。
这就是我现在正在做的事情:
$.ajax({ type: "POST", url: "inc/"+page+".php", data: "id="+encodeURIComponent(pageID), success: function(html){ $("body > .container").html(html); } });
这是我希望能够做到的:
$.ajax({ type: "POST", url: "inc/"+page+".php", data: "id="+encodeURIComponent(pageID), success: function(html){ $("body > .container").html(html); $("title").html(json.PageTitle) } });
在正在返回的页面上,我将指定我想要的标题。 (例如,如果是个人资料,我会返回用户名)
试图混合retun值来包含表示和数据似乎是一种混淆的可能性。 为什么不将它分成两个调用并在另一个成功时获取数据?
就像是:
$.ajax({ type: "POST", url: "inc/"+view_page+".php", data: "id="+encodeURIComponent(pageID), success: function(html) { $("body > .container").html(html); $.ajax({ type: "POST", url: "inc/"+data_page+".php", data: "id="+encodeURIComponent(pageID), success: function(json) { $("title").html(json.PageTitle); } }); });
用JSON包装的HTML和数据
你可以通过返回一个2元素的JSON数组来做到这一点。 第一个元素包含HTML,第二个元素包含另一个包含数据的JSON数组。 你只需要小心打开它而不会破坏任何东西。
服务器端
$html = 'This is Html'; $data = json_encode(array('page_title'=>'My Page')); $response = array('html'=>$html, 'data'=>$data); echo json_encode($response);
客户端
//Ajax success function... success: function(serverResponse){ $("body > .container").html(serverResponse.html); var data = JSON.parse(serverResponse.data); $("title").html(data.page_title) }
注1:我认为这是@hakre在你对你的问题的评论中的意思。
注2:这种方法有效,但我同意@jheddings的说法,避免混合表示和数据可能是一个好主意。 编码业力会回来咬人。
您还可以选择将数据包含在html5数据属性中
例如,如果您要返回动物列表
- Cat
- Dog
...
然后,您可以使用所需的数据收集
$('#ZeAnimals').data('total-animals')
有时将您的请求分成两个不同的ajax调用也是有意义的。
您可以使用自动执行此操作的库,例如http://phery-php-ajax.net 。 运用
Phery::instance()->set(array( 'load' => function(){ /* mount your $html and $json_data */ return PheryResponse::factory() ->json($json_data) ->this() // points to the container ->html($html); } ))->process();
$(function(){ var $container = $('body > .container'); $container.phery('make', 'load'); // or $container.phery().make('load') $container.bind('phery:json', function(event, data){ // deal with data from PHP here }); $container.phery('remote'); });
您也可以使用phery.views
自动加载网站的一部分,而不必担心客户端特定的代码。 在此示例中,您必须在容器, container
上放置一个唯一的ID:
$(function(){ phery.view({ '#container': {} }); });
Phery::instance()->views(array( '#container' => function($data, $params){ /* do the load part in here */ return PheryResponse::factory() ->render_view($html) ->jquery('.title')->text($title); } ))->process();