簡體   English   中英

Ajax響應后腳本未加載

[英]script doesn't load after ajax response

我試圖進行ajax調用並在div類中顯示html部分。 為此,我使用了以下方式。

$.ajax({
    type: "get",
    url: "{{url('searchByCheckbox')}}",
    dataType: 'html',
      success: function(html)
        {
           $(".infinite-scroll").html(html)
        }   
});

但是問題是在html部分中有一個腳本,當我進行第一個ajax調用時,我想加載該腳本,但第二個它已加載了腳本。 假設這樣的html響應:

<script>
  alert()
</script>
// html

我該如何運作? 我將腳本放在html頁面上方,作為響應。

(那些將問題標記為重復的人應至少閱讀我想要的內容和他們想要的內容)

我肯定由於腳本而發生錯誤,因為您正在關閉html內的</script>標簽。

最好的解決方案是將ajax調用中的數據作為json

為此,您應該:

1-如下所示將dataType添加到您的ajax參數:

$.ajax({
    type: "get",
    dataType: "json",

2-在處理ajax調用的php文件中,必須將值作為json重新發送,如下所示:

假設當前您正在執行以下操作:

echo $html

您應該更改它以匹配以下內容:

$retArr = array(
    "html"     => $html, //Your html code without the javascript function
    "jsFunc"   => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;

然后您的ajax success必須如下所示:

success: function(data)
    { //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
       data.jsFunc // Your javascript function params
       $(".infinite-scroll").html(data.html) ;
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM