convert ajax call to angularjs http post

眉间皱痕 提交于 2020-01-03 03:11:05

问题


I have an existing WCF (non-RESTful) service that I'm calling using $.ajax. I need to be able to use $http service. I've tried out a few things, but nothing seems be working. The below snippet returns xml successfully, and I'm ok with it as I can't change the service to return json.

var Type = "POST";
var Url = "http://localhost:83928/BookReviewService.svc";
var Data = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetBookReviews xmlns="http://tempuri.org/"><bookReviewsRequest xmlns:a="http://schemas.datacontract.org/2004/07/BookModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:AmazonCustomerReviewUrl i:nil="true"/><a:AmazonSiteLinkUrl i:nil="true"/><a:Isbn>0393324826</a:Isbn></bookReviewsRequest></GetBookReviews></s:Body></s:Envelope>';
var ContentType = "text/xml; charset=utf-8";
var DataType = "xml";
var ProcessData = true;
CallService();

function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        beforeSend: function (xhr) {
            xhr.setRequestHeader("SOAPAction", "http://tempuri.org/IBookReviewService/GetBookReviews");
        },
        success: function (msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result) {
    console.log(result);
    console.log('Service call failed: ' + result.status + ' ' + result.statusText);
}

function ServiceSucceeded(result) {
    console.log(result);
}

回答1:


Your question reads "convert ajax call to angularjs http post".

To start with you should create a service/factory for all your ajax operations, but that's just a personal preference, would work without that too, read this if you don't want to use service/factory and do directly instead.

angular.module("moduleName").factory('factoryName', ['$http', function ($http) {
    return {
        myFunction: function(data) {
            return $http({
                url: '/user/update',
                method: 'POST',
                data: data
            });
        }
    };
}]);

and in your controller, inject this service and use this function like

factoryName.myFunction();

Ofcourse with a success/error callbacks if needed.



来源:https://stackoverflow.com/questions/32132171/convert-ajax-call-to-angularjs-http-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!