Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

从前端网页调用服务器方法

$
0
0

想法:用nodejs搭建一个服务器,包含一个加法计算,对外公布。 从网页端输入两个数字后,在点击‘=’时把输入的两个数字POST到服务端并返回结果到前端。

以下做法是否存在问题呢,请大神帮忙,谢谢! 做法:①搭建服务端代码service.js: var soap = require(‘soap-server’); function MyTestService() { } MyTestService.prototype.getResult = function(value1, value2) { return parseFloat(value1) + parseFloat(value2); }; var soapServer = new soap.SoapServer(); var soapService = soapServer.addService(‘testService’, new MyTestService()); soapServer.listen(3000); console.log(“Web service start”); ②服务开启后,通过URL:“ http://localhost:3000/testService?wsdl”能查看到服务端的wsdl文件。③从前端JS中请求服务器 function requestByPost(v1, v2, url) { createXMLHttpRequest(); var data; data = ‘<?xml version=“1.0” encoding=“utf-8”?>’; data = data + ‘<soap:Envelope xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema” xmlns:soap=“http://www.w3.org/2001/12/soap-envelope”>’; data = data + ‘soap:Body’; data = data + ‘<getResult>’; data = data + ‘<value1>’+v1+’</value1>’; data = data + ‘<value2>’+v2+’</value2>’; data = data + ‘</getResult>’; data = data + ‘</soap:Body>’; data = data + ‘</soap:Envelope>’; alert(data);

xmlhttp.onreadystatechange = handleStateChange;
xmlhttp.Open("POST", url, true);
xmlhttp.SetRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.SetRequestHeader("SOAPAction", getResult);
xmlhttp.Send(data);
alert("send over");

}


Viewing all articles
Browse latest Browse all 14821

Trending Articles