簡體   English   中英

如何從URL獲取動態值

[英]How to get dynamic value from URL

我正在研究AngularJS,我希望從URL中加載MySQL中的內容。

我使用的AngularJS RouteProvider是這樣的:

$routeProvider.when('/page/pages=:pages', {
     templateUrl: 'page.html',
     reloadOnSearch: false
});

我的動態網址是:

"<a class='list-group-item' href='#/page/pages=" + slug + "'>" +
    title + " <i class='fa fa-chevron-right pull-right'></i>" +
"</a>"

之后,我嘗試提醒PhoneGap上的URL位置(附上截圖)

在此輸入圖像描述

現在,我想將此頁面值傳遞給AJAX,以便從MySQL獲得結果查詢。

$(function ()
{
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    jQuery.ajax({

        url: 'http://keralapsctuts.com/app/index.php', //the script to call to get data          
        data: "pages="+pages, //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
        type: "POST",   
        dataType: 'json',           //data format 
        success:function(data) {
            var result = "";
            var title = "";

            alert(pages);

            for(var i=0; i < data.length; i++) {
                var title = data[i]["pagetitle"];        //get name
                var content = data[i]["pagecontent"];        //get slug
                result += +content;
                title += "<span>"+title+"</span>";
            }

            $('#pcontent').html(content); //Set output element html
            $('#ptitle').html(title); //Set output element html
        }
    });
}); 

我沒有得到任何輸出。

要獲取URL中的查詢參數,請使用AngularJS $位置提供程序。 如果您的網址看起來像example.com/#/page?pages=5,則可以通過編寫獲取值5

 var urlPageValue = $location.search()["pages"];

請務必通過編寫在控制器中包含$ location和$ http服務

yourModuleName.controller("AwesomeController", ["$location", "$http", function($location, $http){
    // Page initialization code (like your ajax call) here
}])

然后,正如Szanto建議的那樣,使用$ http服務通過寫入來執行ajax調用

$http({
    url:"/yourApiEndpoint",
    method: "POST",
    data: { pages: urlPageValue }
}).success(function(response){
    // Handle returned data here
}).error(function(){
    // Handle errors here
})

最后,在您的原始問題中,當您從SQL調用中獲取數據時,您手動將跨度添加到DOM。 如果要使用AngularJS,則應將響應分配給數組變量,並使用HTML中的ngRepeat指令為數組中的每個項實例化一些模板。

你正在使用Angular和jQuery? 這是一個壞主意,使用Angular的內置http 方法來替換jQuery ajax請求。 其次,您可以將參數傳遞給請求配置(即使在jQuery中)。

暫無
暫無

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

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