2013-08-20 41 views
0

下面的代碼是我實現中的ajax調用的響應。 /* response of ajax call */ <script> var count = 6; </script> <div> some code goes here</div>如何從ajax響應獲取特定值

如何從jQuery的Ajax響應

$.ajax({ 
     url: url, 
     type: "GET", 
     dataType: "text", 
     timeout: 20000, 
     success: function(response){ }, 
     error: function(){/* error code goes here*/} 
    }); 

回答

1

嘗試使用改變你的服務器如何把Ajax響應的方式,例如上述計數值JSON:

{ 
    "data": { 
     "count": 6 
    }, 
    "html": "<div>some code goes here</div>" 
} 

然後使用以下腳本訪問計數器:

$.getJSON({ 
    url: url, 
    timeout: 20000, 
    success: function(response) { 
     console.log(response.data.count); 
    }, 
    error: function() {/* error code goes here*/} 
}); 
+0

謝謝J.M的回覆。響應以html的形式出現,它包含具有計數值的腳本標記,需要訪問該計數值,並且ajax dataType是文本。 – shi69

+0

你不能改變響應類型嗎? – Jublo

0

如果你必須接受提到字符串形式返回值和提煉,從它的計數值,則正則表達式節省了一天:

var COUNT_DIGIT_EXPRESSION = /count\s?=\s(\d+);/i; 

$.ajax({ 
    url: url, 
    type: "GET", 
    dataType: "text", 
    timeout: 20000, 
    success: function(response){ 
    var countMatch = response.responseText.match(COUNT_DIGIT_EXPRESSION); 
    var countInt; 

    // Return val from match is array with second element being the matched 
    // capturing subgroup (\d+), which is the digit or digits themselves. 
    if (countMatch && countMatch.length == 2) { 
     countInt = parseInt(countMatch[1], 10); 
    } 
    console.log('Count value is ' + countInt); 
    }, 
    error: function(){/* error code goes here*/} 
}); 
0

有了您的響應是整個文本:

<script> var count = 6; </script> <div> some code goes here</div> 

使用此代碼來獲取指定標籤的結果:

var resultmatch = xmlHttpReq.responseText.match(/<script>(.*?)<\/script>/); 

如果再有:

echo resultmatch; 

將輸出:

var count = 6; 

= = =

但既然你要計數的值,用一個語句做這樣:

eval(xmlHttpReq.responseText.match(/<script>(.*?)<\/script>/)); 

這將導致在您的html頁面顯示JavaScript,var count = 6;就好像它已經被輸入爲代碼一樣。所以,現在你有一個變量名爲與值,你可以隨心所欲地使用它。

如果然後做:

echo count; 

將輸出:

6 

當然,您可以使用變量計數在繼續JavaScript才能使用它的值。

相關問題