Angular Js初学者Ajax调用

Angular Js beginner Ajax Call

本文关键字:调用 Ajax 初学者 Js Angular      更新时间:2023-09-26

我是angular js的新手,在我的controller.js中有我的应用程序的控制器,它100%正常工作。我遇到的问题是如何使用angular js进行ajax调用。我正在尝试从我的服务中获取数据,并使用这个ajax将其传递到我的index.html。当我尝试调试代码时,它只命中$http,但没有遍历其中的代码。我做错了什么?

$http({
        method: 'POST',
        url: 'http://someService.site.net/site.aspx',
        data:{action:'someAction', position:'founders'},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response){
        var json =jQuery.parseJSON(response);
        var htmldata="";
        for(i=0; i<json.length; i++)
        {
            var htmlInfo = '<li><div class=''col''><a href="'+ json[i].Id +'"><img width=''100%'' height=''auto'' src="'+json[i].Image + '" class=''profile-img'' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></a></div></li>';
            htmldata+= htmlInfo;
        }
        jQuery("#vflist").html(htmldata);
    }, function errorCallback(response){
    });

在成功和错误回调上标记断点。

$http是一项服务。您在它的参数中传递了所需的数据。

$http({})
       ^options

在调用这个$http之后,它将完成它的工作,并异步地向提供的url发送请求。但您不需要调试该部分。

$http({options})
    .then(function(data){ 
        // mark 1 breakpoint here
    }, function(data){
        // mark another breakpoint here
    })

由于您已经在使用jQuery和Angularjs,我建议您使用$.params()函数对参数数据进行编码。你的$http就像

$http({
    method: 'POST',
    url: 'http://someService.site.net/site.aspx',
    data:$.params({action:'someAction', position:'founders'}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

此外,我建议您使用Angular方式来做事,而不是使用jQuery。你甚至可能喜欢它;)

第一件事是:您可以简单地使用$http函数,如下所示:

var config = {
    headers : {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}};
$http.post('http://someService.site.net/site.aspx',
           {action:'someAction', position:'founders'},
           config)
     .success(function(response) {
        var json =jQuery.parseJSON(response);
        var htmldata="";
        for(i=0; i<json.length; i++) {
            var htmlInfo = '<li><div class=''col''><a href="'+ json[i].Id +'"><img width=''100%'' height=''auto'' src="'+json[i].Image + '" class=''profile-img'' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></a></div></li>';
            htmldata+= htmlInfo;
        }
        jQuery("#vflist").html($sce.trustAsHtml(htmldata));
     })
     .error(function(data, status, headers, config) {
          console.log(status);
     });

其次,正如您在上面的代码中看到的,我使用了$sce.trustAsHtml()——当您通过$http将一些html推送到DOM时,这是必需的——或者它只会显示带有标记的代码。您必须在控制器定义中注入$sce

在调用ajax之前放一行这对我来说很有效希望你能

$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
// YmVlcDpib29w you can put any string

这也在——https://docs.angularjs.org/api/ng/service/$http