【问题标题】:View Source: JSON Response is showing instead of HTML source code查看源代码:显示 JSON 响应而不是 HTML 源代码
【发布时间】:2019-02-24 07:22:39
【问题描述】:

因此,当我查看我的页面源代码时,将显示 json 响应(也就是我正在检索的表)而不是 html 页面。

我一开始一直试图弄清楚如何在仍然呈现 HTML 的同时检索 json 响应,这让我想出了这个控制器代码。想帮助如何改进我的代码来解决这个问题。将不胜感激的建议!

我的控制器:

$products = Product::all();
    if (\Illuminate\Support\Facades\Request::ajax())
      return response()->json($products);
    else
      return view('products.index');

jQuery 脚本:

$(document).ready( function () {

var pathname = window.location.pathname;


  loadProducts();

function loadProducts(){
var columns = [{
        "sTitle": "Name",
        "mData": "name"
    }, {
        "sTitle": "Price",
        "mData": "price"
    }, {
        "sTitle": "Category_ID",
        "mData": "category_id"
    }, {
        "sTitle": "Supplier_ID",
        "mData": "supplier_id"
    }]

$.ajax({
    'url': '{{ url('products') }}',
    'method': "GET",
    'contentType': 'application/json'
}).done( function(data) {
      var example_table = $('#myTable').DataTable({
        "aaData": data,
        "columns": columns
      });
 });
 }

【问题讨论】:

    标签: javascript jquery html json laravel


    【解决方案1】:

    我建议你使用DataTableJSONP data source for remote domains

    $(document).ready(function() {
        $('#example').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "scripts/jsonp.php",
                "dataType": "jsonp"
            }
        } );
    } );
    

    【讨论】:

      猜你喜欢
      • 2012-07-30
      • 2011-08-08
      • 2013-07-28
      • 2016-07-07
      • 2010-12-21
      • 2018-11-29
      • 2014-08-30
      • 2011-06-09
      • 1970-01-01
      相关资源
      最近更新 更多