亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

重定向到 json 響應中的 URL

重定向到 json 響應中的 URL

PHP
楊__羊羊 2022-01-08 20:35:51
我有兩個文件 fetch.php 和 index.php。fetch.php 文件進行搜索并將結果轉換為 Json。Index.php 具有循環遍歷 Json 結果的 Jquery。其中一個單元格包含一個 URL。如何讓用戶重定向到 URL。//index.php==============================<script>$(document).ready(function(){ function load_data(query) {  $.ajax({   url:"fetch.php",   method:"POST",   data:{query:query},   dataType:"json",   success:function(data)   {    $('#total_records').text(data.length);    var html = '';    if(data.length > 0)    {     for(var count = 0; count < data.length; count++)     {      html += '<hr>';      html += '<tr>';      html += '<div>'+data[count].title+'</div>';      html += '<td>'+data[count].book+'</td><tr/>';       html += '<br/><td>'+data[count].description+'</td><tr/>';      html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button       html += '<hr>';     }    }    else    {     html = '<tr><td colspan="5">No Data Found</td></tr>';    }    $('tbody').html(html);   }  }) } $('#search').click(function(){  var query = $('#search_id').val();  load_data(query); });</script>
查看完整描述

2 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

簡單的解決方案:

html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';



查看完整回答
反對 回復 2022-01-08
?
米脂

TA貢獻1836條經驗 獲得超3個贊

考慮以下建議:


$(function() {

  function load_data(q) {

    $.ajax({

      url: "fetch.php",

      method: "POST",

      data: {

        query: q

      },

      dataType: "json",

      success: function(data) {

        $('#total_records').text(data.length);

        var row;

        if (data.length > 0) {

          $.each(data, function(k, d) {

            row = $("<tr>");

            $("<td>").html(d.title).appendTo(row);

            $("<td>").html(d.book).appendTo(row);

            $("<td>").html(d.description).appendTo(row);

            var e = $("<td>").appendTo(row);

            $("<button>").html("VIEW").click(function(e) {

              window.location.href = d.url;

            }).appendTo(e);

          });

        } else {

          row = $("<tr>");

          $("<td>", {

            colspan: 4

          }).html("No Results Found.").appendTo(row);

        }

      }

    });

  }


  $('#search').click(function() {

    var query = $('#search_id').val();

    load_data(query);

  });

});

如您所見,這使用了更多的 jQuery 部件來幫助精簡您的代碼。此外,當按鈕被創建并添加到表中時,我們會創建一個 Click 事件回調。


你有很多不正確的 HTML 語法。我的例子沒有復制這一點。行元素應該包含單元格而不是其他元素。是的,你可以做到,但這不是一個好習慣。這就是我刪除它們的原因。如果出于某種原因需要它們,您應該提供一個更完整的示例,以便清楚為什么需要它們。


查看完整回答
反對 回復 2022-01-08
  • 2 回答
  • 0 關注
  • 203 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號