douge3492 2016-11-10 10:26
浏览 45
已采纳

如何在AJAX响应中返回数组和HTML数据?

I have an array like this in my PHP page named new1.php:

$arr = ['value 1', 'value 2', 'value 3'];
$html = '<div>huge data with all tags like a page</div>';
$response = json_encode('array' => $arr, 'html' => $html);
echo $response

In the calling page, when I console.log(data.html) it gives undefined. The same happens for console.log(data.array);. Here is my AJAX code:

$.ajax({
    url: "new1.php",
    type: "POST", 
    data: { somedata: somedata },
    dataType: "text",
    success: function(data) {
        console.log(data);
        console.log(data.html);
        console.log(data.array);
    }
});

Most importantly, I want to know what is the best way to return a page with other data from AJAX response?

  • 写回答

2条回答 默认 最新

  • dongpan9760 2016-11-10 10:38
    关注

    from your php code where you do json_encode add this to the top of the page header("Content-Type: application/json"); then your encode should take in array as parameter instead

    json_encode(array("array"=>$arr, "html"=>$html));

    it should see your record as json now and please change ur dataType to json from Jquery intelligence guess from the server state (jquery) it will automatically take json instead

    dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程