如何将参数从客户端传递到http适配器 [英] how to pass parameters from client side to the http adapter

查看:133
本文介绍了如何将参数从客户端传递到http适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够从我的适配器中的SOAP服务获得响应,但是从客户端我无法将参数传递给适配器。我可以使用 alert 显示值,但我无法将它们传递给 params 变量。任何人都可以帮忙吗?

I am able to get a response from a SOAP service in my adapter but from the client side I am having trouble passing the parameters to the adapter. I'm able to display the values using alert but I can't pass them to the params variable. Can anyone help?

Javascript代码(应用):

/**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

currentPage = {};

currentPage.init = function(){
    WL.Logger.debug("MainPage :: init");
};

function validate(){

    alert("hello" +$('#username').val());
    alert("hai" +$('#userpwd').val());
     busyIndicator.show();
     var params = {"process": {"username":"$('#username').val()","userpwd":"$('#userpwd').val()"}};
        //{"process":{"username":"user","userpwd":"pass"}}it works
                var invocationData = {
                adapter : 'SoapAdapter1',
                procedure : 'userlogin_ep_process',
                parameters : [params]
            };
        //{"process":{"username":"user","userpwd":"pass"}}it works
        WL.Client.invokeProcedure(invocationData,{
            onSuccess : loadFeedsSuccess,
            onFailure : loadFeedsFailure
        });
    }

    function loadFeedsSuccess(result){
        WL.Logger.debug("Feed retrieve success");
        busyIndicator.hide();
        if (result.invocationResult.Items.length>0) 
            displayFeeds(result.invocationResult.Items);
        else 
            loadFeedsFailure();
    }

    function loadFeedsFailure(result){
        WL.Logger.error("Feed retrieve failure");
        busyIndicator.hide();
        WL.SimpleDialog.show("Inquiry", "Service not available. Try again later.", 
                [{
                    text : 'Reload',
                    handler : WL.Client.reloadApp 
                },
                {
                    text: 'Close',
                    handler : function() {}
                }]
            );
    }

HTML代码:

<label>username</label> <input type="text" id="username"><br><br>
<label>password</label> <input type="text" id="userpwd"><br><br>
<input type="submit" value="login" onclick="validate();">

适配器代码:

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generated code - Do not edit                                                                                  //
//                                                                                                               //
// This is a SOAP adapter that was auto-generated by Worklight for invocation of specific SOAP-based services.   //
// The adapter may invoke more than one service as long as they are all from the same enpdpoint (server host).   //
// Each adapter procedure matches a single operation for the same endpoint server and accepts:                   //
//   params  - Serialized JSON representation of the XML-based SOAP body to be sent to the service               //
//   headers - Custom HTTP headers to be specified when invoking the remote service. It is a JSON object with    //
//             the headers names and values. E.g. { 'name1' : 'value1', 'name2' : 'value2' }                     //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function userlogin_ep_process(params, headers){
    var soapEnvNS = '';
    // The value of 'soapEnvNS' was set based on the version of the SOAP to be used (i.e. 1.1 or 1.2).
    soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';

    // The following mappings object was autogenerated from the XML schema of the input message to the service.
    // It is being used to support a params JSON when invoking this procedure that don't specify the namespace
    // prefix nor specifying whether a property is attribute or not.
    // 
    // The 'roots' object has the list of message parts within the invocation SOAP message. Each entry has a
    // mapping between the root element name and its namespace prefix and type.
    // Each root object may define 'nsPrefix' and 'type'. Both are optional - If there is no need for a NS prefix
    // then the 'nsPrefix' should not be specified. If the element is a simple type then the 'type' should not be
    // specified.
    //
    // The 'types' object has a list of types each defining the children of the type and the definition of each
    // child. If the child is a complext type, the 'type' property has a reference to the child type definition.
    // Each child object may define:
    // 'nsPrefix' (optional) - Holds the namespace prefix to be attached to the element. If there is no need for 
    //   a NS prefix then the 'nsPrefix' should not be specified. 
    // 'type' (optional) - If the element is a simple type then the 'type' should not be specified. If it is an 
    //   attribute then 'type' should have the value of '@'. Otherwise the value of 'type' is a reference to the 
    //   type definition within the 'types' object.
    var mappings = {
        roots: {
            'process': { nsPrefix: 'client', type: 'client:process' }               
        },

        types: {
            'client:process': {
                children: [
                    {'username': { nsPrefix: 'client' }},   
                    {'userpwd': { nsPrefix: 'client' }} 
                ]
            }
        }
    };
    var namespaces = 'xmlns:client="http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessUserLogin" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" ';
    var request = buildBody(params, namespaces, mappings, soapEnvNS);
    var soapAction = 'process';
    return invokeWebService(request, headers, soapAction);
}



function buildBody(params, namespaces, mappings, soapEnvNS){
    var body =
        '<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
        '<soap:Body>\n';

    var fixedParams = {};
    for (var paramName in params) {
        if (mappings['roots'][paramName]) { //There is mapping for this param
            var root = mappings['roots'][paramName];
            var name = paramName;
            if (root['nsPrefix'])
                name = root['nsPrefix'] + ':' + paramName;
            fixedParams[name] = handleMappings(params[paramName], root['type'], mappings['types']); 
        }
        else {
            fixedParams[paramName] = params[paramName];
        }
    }

    body = jsonToXml(fixedParams, body, namespaces);

    body += 
        '</soap:Body>\n' +
        '</soap:Envelope>\n';
    return body;
}

function handleMappings(jsonObj, type, mappings) {
    var fixedObj = {};
    var typeMap = mappings[type]['children']; //Get the object that defines the mappings for the specific type

    // loop through the types and see if there is an input param defined
    for(var i = 0; i < typeMap.length; i++) {
        var childType = typeMap[i];

        for(var key in childType) {
            if(jsonObj[key] !== null) { // input param exists
                var childName = key;
                if (childType[key]['nsPrefix'])
                    childName = childType[key]['nsPrefix'] + ':' + key;

                if (!childType[key]['type']) //Simple type element
                    fixedObj[childName] = jsonObj[key];
                else if (typeof jsonObj[key] === 'object' && jsonObj[key].length != undefined) { //Array of complex type elements
                    fixedObj[childName] = [];
                    for (var i=0; i<jsonObj[key].length; i++)
                        fixedObj[childName][i] = handleMappings(jsonObj[key][i], childType[key]['type'], mappings);
                }
                else if (typeof jsonObj[key] === 'object') //Complex type element
                    fixedObj[childName] = handleMappings(jsonObj[key], childType[key]['type'], mappings);
                else if (childType[key]['type'] == '@') //Attribute
                    fixedObj['@' + childName] = jsonObj[key];
            }
        }
    }

    return fixedObj;
}

function getAttributes(jsonObj) {
    var attrStr = '';
    for(var attr in jsonObj) {
        if (attr.charAt(0) == '@') {
            var val = jsonObj[attr];
            attrStr += ' ' + attr.substring(1);
            attrStr += '="' + xmlEscape(val) + '"';
        }
    }
    return attrStr;
}

function jsonToXml(jsonObj, xmlStr, namespaces) {
    var toAppend = '';
    for(var attr in jsonObj) {
        if (attr.charAt(0) != '@') {
            var val = jsonObj[attr];
            if (typeof val  === 'object'  &&  val.length != undefined) {
                for(var i=0; i<val.length; i++) {
                    toAppend += "<" + attr + getAttributes(val[i]);
                    if (namespaces != null)
                        toAppend += ' ' + namespaces;
                    toAppend += ">\n";
                    toAppend = jsonToXml(val[i], toAppend);
                    toAppend += "</" + attr + ">\n";
                }
            }
            else {
                toAppend += "<" + attr;
                if (typeof val  === 'object') {
                    toAppend += getAttributes(val);
                    if (namespaces != null)
                        toAppend += ' ' + namespaces;
                    toAppend += ">\n";
                    toAppend = jsonToXml(val, toAppend);
                }
                else {
                    toAppend += ">" + xmlEscape(val);
                }
                toAppend += "</" + attr + ">\n";
            }
        }
    }
    return xmlStr += toAppend;
}


function invokeWebService(body, headers, soapAction){
    var input = {
        method : 'post',
        returnedContentType : 'xml',
        path : '/soa-infra/services/Mobile/AbsManagement/userlogin_ep',
        body: {
            content : body.toString(),
            contentType : 'text/xml; charset=utf-8'
        }
    };

    //Adding custom HTTP headers if they were provided as parameter to the procedure call
    //Always add header for SOAP action 
    headers = headers || {};
    if (soapAction != 'null')
        headers.SOAPAction = soapAction;
    input['headers'] = headers;

    return WL.Server.invokeHttp(input);
}

function xmlEscape(obj) {
    if(typeof obj !== 'string') {
        return obj;
    }
    return obj.replace(/&/g, '&amp;')
           .replace(/"/g, '&quot;')
           .replace(/'/g, '&apos;')
           .replace(/</g, '&lt;')
           .replace(/>/g, '&gt;');
}


推荐答案

问题在于您将字段值传递给 params 对象的方式。如果用引号括起javascript表达式,那么它不再是表达式,而是字符串。

The problem lies in the way you are passing the field values to the the params object. If you wrap a javascript expression in quotes then it's not longer an expression, it's a string.

您应该更改验证函数,如下所示:

You should change your validate function as follow:

function validate(){

    var username = $('#username').val();
    var password = $('#userpwd').val();

    busyIndicator.show();

    var params = {
        "process": {
            "username": username,
            "userpwd": password
        }
    };

    var invocationData = {
        adapter : 'SoapAdapter1',
        procedure : 'userlogin_ep_process',
        parameters : [params]
    };

    WL.Client.invokeProcedure(invocationData,{
        onSuccess : loadFeedsSuccess,
        onFailure : loadFeedsFailure
    });
}

PS:我同意@Idan你应该只保留一个问题因为另一个问题是针对同一问题的。

PS: I agree with @Idan you should keep only one question because the other questions is for same issue.

这篇关于如何将参数从客户端传递到http适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆