从AJAX调用Web服务

时间:2014-01-31 16:13:43

标签: java jquery ajax

我通过AJAX查看了一些关于调用WS的帖子/教程,但我仍然无法做到这一点。不是环境很重要,而是...我在Eclipse中编写了我的Java类,我在GlassFish上运行它,我可以通过soapUI访问端点。

JAVA课程:

package com.tester.gf;

import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;

@WebService
public class GlassFishTestApp {

    public List<String> getBrands() {
        List<String> brands = new ArrayList<>();
        brands.add("Chevrolet");
        brands.add("Dodge");
        brands.add("Ford");
        return brands;
    }
}

端点:

localhost:8080/GlassFishTestApp/GlassFishTestAppService?wsdl

当我加载以下网页时,我只会在。

中看到“错误:”
<html>
    <head>
        <title>SOAP WS Test</title>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $.ajax(
                    type: 'get',
                    url: 'http://localhost:8080/GlassFishTestApp/GlassFishTestAppService',
                    success: function (data) {
                        $('#results').text(data);
                    },
                    error: function (request, status, error) {
                        $('#results').text('Error: ' + request.responseText);
                    }
                });
            });
        </script>
    </head>
    <body>
        <div id="results"></div>
    </body>
<html>

soapUI请求:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:gf="http://gf.tester.com/">
    <soapenv:Header/>
        <soapenv:Body>
            <gf:getBrands/>
        </soapenv:Body>
</soapenv:Envelope>

soapUI Respose:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:getBrandsResponse xmlns:ns2="http://gf.tester.com/">
             <return>Chevrolet</return>
             <return>Dodge</return>
             <return>Ford</return>
        </ns2:getBrandsResponse>
    </S:Body>
</S:Envelope>

感谢您的任何意见!

1 个答案:

答案 0 :(得分:0)

知道了!

var soapMessage =
    '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:gf="http://gf.tester.com/">' +
        '<soapenv:Header/>' +
            '<soapenv:Body>' +
                '<gf:getBrands/>' +
            '</soapenv:Body>' +
    '</soapenv:Envelope>';

$.ajax({
    url: "/GlassFishTestApp/GlassFishTestAppService",
    type: "POST",
    dataType: "xml",
    contentType: "text/xml; charset=\"utf-8\"",
    headers: {
        SOAPAction: "/GlassFishTestApp/GlassFishTestAppService/getBrands"
    },
    data: soapMessage,
    success: function(data) {
        $('#results').text(data);
    },
    error: function (request, status, error) {
        $('#results').text('Error: ' + error);
    }
});