如何从javascript向webservice发送GET请求

时间:2014-11-11 09:15:32

标签: javascript html

我有一个html表单,其上有一个onClick属性' s按钮,然后调用一个javascript函数:

function submitForm () {

    // Get Session ID
    var sessionId = document.getElementById("session-id").value;

    // Get Description
    var description = document.getElementById("description").value;

    // Call WebService ??   

}

在此阶段,我必须通过以下网址拨打网络服务:

localhost:8080/PatientRefund/WebService?urnId=93&batchDescription=My%20Description

你可以替换的地方' 93'与' sessionId'和我的%20描述'使用' batchDescription'。请求也应该是GET请求。

有人能指出我正确的方向吗?我不是在找你为我编写代码......谢谢你们:)

1 个答案:

答案 0 :(得分:1)

使用jQuery ajax,您的代码将如下:

function submitForm () {
    var sessionId = document.getElementById("session-id").value;
    var description = document.getElementById("description").value;

    $.ajax({
        url: 'http://localhost:8080/PatientRefund/WebService',
        type: 'GET',
        data: {urnId: sessionId, batchDescription: description}
    }).done(function(response) {
        console.log(response);
        // do something with your response
    });
}

如果您希望客户端在提交后下载文件,则不应使用ajax请求。您应该动态创建表单并提交它。示例代码:

function submitForm() {
    var sessionId = document.getElementById("session-id").value;
    var description = document.getElementById("description").value;
    var newForm = jQuery('<form>', {
        'action': 'http://localhost:8080/PatientRefund/WebService',
        'method': 'GET',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'urnId',
        'value': sessionId,
        'type': 'hidden'
    })).append(jQuery('<input>', {
        'name': 'batchDescription',
        'value': description,
        'type': 'hidden'
    }));
    newForm.submit();
    return false;
}
相关问题