2016-11-26 35 views
1

我想從getJSON調用中更改href值。以下工作在通話之外,但不在裏面。有任何想法嗎?

$("#tweetButton").prop("href", "https://twitter.com/intent/tweet?text=test&url=%20&hashtags=quotes"); 

HTML:

<div id="quote"> 
    <div id="quoteText"> 
     Test 
    </div> 
    </br> 
    <a id="tweetButton" href="https://twitter.com/intent/tweet?text=&url=%20&hashtags=quotes" class="twitter-share-button">Tweet</a> 
    <button id="btnNewQuote">New Quote</button> 
</div> 

的jQuery:

$(document).ready(function() { 
    $.ajaxSetup({ cache: false }); 
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {  
     $("#tweetButton").prop("href", "https://twitter.com/intent/tweet?text=test&url=%20&hashtags=quotes"); 
     $("#quoteText").html(a[0].content + "<p>— " + a[0].title + "</p>"); 
     // $("#tweetButton").attr("href", "https://twitter.com/intent/tweet?text=" + encodeURI(a[0].content) + encodeURI(" -") + a[0].title + "&url=%20&hashtags=quotes"); 
    }); 

    $("#btnNewQuote").click(function(){ 
     $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) { 
      $("#quoteText").html(a[0].content + "<p>— " + a[0].title + "</p>"); 
      $("#tweetButton").prop("href", "https://twitter.com/intent/tweet?text=test&url=%20&hashtags=quotes"); 
     }); 
    }); 
}); 

回答

2

href不是屬性,它是一個屬性。使用.attr()而不是.prop()


在jQuery的文檔的 .getJSON(),它說:

如果JSON文件包含語法錯誤,請求通常會失敗默默。

因此,如果返回的結果是無效的JSON,您的成功函數將不會運行,並且您不會看到任何其他指示器出現問題。

我懷疑這是你的問題是由於包括您的網址&callback=。對於理解JSONP(不,這不是打字錯誤)調用的服務,這會將返回的JSON對象包裝在圓括號中,因爲您本質上要求將JSON對象包裝在函數調用中而不給函數名稱。這會導致無效的語法。

你不能只是刪除callback因爲JSONP的整點是讓跨域請求(您正試圖)。 jQuery需要知道你正在做什麼,並且$.getJSON()沒有設置來處理這種事情。

你需要這樣的安排你的代碼:

$.ajax({ 
    type:"GET", 
    url: "//quotesondesign.com/wp-json/posts", 
    jsonp: "callback", 
    crossDomain: true, 
    data: { 
     filter: { 
      orderby: "rand", 
      posts_per_page: 1 
     } 
    }, 
    success: function(response) { 
     console.log(response); // javascript object representing response 
    }, 
    error: function() { 
     console.log('error'); 
    } 
}); 
+0

感謝,但是,.attr()未調用的getJSON裏面工作,要麼,但外面工作正常。 第二個答案在這裏:http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery指示使用.prop()爲jQuery 1.6及以上 – RoyalKing

+0

@RoyalKing更新 – Ouroborus

+0

有趣的是,我在API的開發者網站(https://quotesondesign.com/api-v4-0/)上找到了getJSON代碼。話雖如此,我將我的代碼切換到直接使用您的ajax代碼,並嘗試使用.attr()修改href值。同樣,它在ajax調用之外工作,但不在成功之內(而成功內部的其他語句正常工作)。 – RoyalKing

0

這最終是一個CodePen問題。我測試JSBin,直接使用getJSON和ajax,它工作正常!

相關問題