2011-06-06 159 views
0

我有一個PHP SOAP Web服務充當中繼來調用跨域Web服務。我遇到的問題是從JavaScript調用本地PHP Web服務方法(使用JQuery/Ajax)。我想在我的Web服務中調用特定的方法;例如「LoginToAccount」;從JQuery(Ajax)調用PHP SOAP Web服務

我沒有興趣在url中追加params,然後找出調用哪個方法......這在.NET(mywebservice.asmx/LoginToAccount「)中是非常直接的,但無法弄清楚如何得到這個在PHP工作

我不斷收到「錯誤的請求」的「500內部服務器錯誤」: 壞請求

這是我的PHP代碼:

<?php 

function LoginToAccount($email, $passCodeHash) { 
    //...code calling cross-domain web services 
    return $jsonEncodedResponse; 
    } 


function CreateAccount($email, $passCodeHash){ 
    //...code calling cross-domain web services 
    return $jsonEncodedResponse; 
} 

$server = new SoapServer(null, array('uri' => "http://www.myurl/webservices/")); 

$server->addFunction('LoginToAccount'); 
$server->addFunction('CreateAccount'); 
$server->handle(); 
?> 

這裏我的JavaScript代碼:

function AjaxCall() { 
    $.ajax({ 
     type: "POST", 
     url: "phpRelay.php/LoginToAccount", 
     data: "{email : '[email protected]', passCodeHash: '12345'}", 
     contentType: "application/json", 
     dataType: "json", 
     success: succeeded, 
     error: queryError 
    }); 
} 

function succeeded(data, textStatus, request) { 
    var result = $.parseJSON(data.d); 

} 

function queryError(request, textStatus, errorThrown) { 
    alert(request.responseText, textStatus + " " + errorThrown); 
} 

這些都在同一個域中。謝謝!

+1

據我所知,內置皁服務器只能處理XML,JSON不,還是我錯了? – Wrikken 2011-06-06 17:04:38

回答

1

,而不是使用PHP SoapServer時,你可以用下面的代碼替換它的:

echo $data = (function_exists($_SERVER['QUERY_STRING'])) ? json_encode(array('d'=>$_SERVER['QUERY_STRING'](file_get_contents('php://input')))) : 'error: function does not exists'; 

它的作用是使用QUERY_STRING作爲函數名。它首先檢查函數是否存在,如果沒有打印錯誤,但是如果存在,則以字符串格式調用發佈數據作爲條件的函數。最後,函數的返回數據被打印爲一個json數組,結果集爲d。

所以你的JavaScript應該如下(注意URL調用應符合而不是/前的功能?):

function AjaxCall() { 
    $.ajax({ 
     type: "POST", 
     url: "phpRelay.php?LoginToAccount", 
     data: "{email : '[email protected]', passCodeHash: '12345'}", 
     contentType: "application/json", 
     dataType: "json", 
     success: succeeded, 
     error: queryError 
    }); 
} 

function succeeded(data, textStatus, request) { 
    var result = $.parseJSON(data.d); 

} 

function queryError(request, textStatus, errorThrown) { 
    alert(request.responseText, textStatus + " " + errorThrown); 
} 

希望這可以幫助你!我知道發佈這個有點晚,但是如果有其他人需要這樣的東西,我就發佈它!我需要它,不能解決這樣的問題,所以我不得不自己制定解決方案。

歡呼 c_bb

0

我試圖與Ajax客戶端SOAP PHP服務器,發現從Here

工作代碼

首先下載的NuSOAP庫,然後創建server.php

<?php 
//call library 
require_once ('lib/nusoap.php'); 

// Define the TriangleArea method as a PHP function 
function TriangleArea($b, $h) { return 'The triangle area is: ' .(($b*$h)/2); } 
// Define the RectangleArea method as a PHP function 
function RectangleArea($L, $l) { return 'The rectangle area is: ' .($L*$l); } 
// create the function 
function get_message($your_name) 
{ 
if(!$your_name){ 
return new soap_fault('Client','','Put Your Name!'); 
} 
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP"; 
return $result; 
} 


//using soap_server to create server object 
$server = new soap_server; 

// Initialize WSDL support 
$server->configureWSDL('mathwsdl', 'urn:mathwsdl'); 


// Register the TriangleArea method 
    $server->register('TriangleArea',     // method name 
     array('b' => 'xsd:int', 'h' => 'xsd:int'),  // input parameters 
     array('area_t' => 'xsd:string'),    // output parameters 
     'urn:mathwsdl',        // namespace 
     'urn:mathwsdl#TriangleArea',     // soapaction 
     'rpc',           // style 
     'encoded',          // use 
     '1=> : Calculate a triangle area as (b*h)/2'   // documentation 
    ); 

    // Register the RectangleArea method to expose 
    $server->register('RectangleArea',     // method name 
     array('L' => 'xsd:int', 'l' => 'xsd:int'),  // input parameters 
     array('area_r' => 'xsd:string'),    // output parameters 
     'urn:mathwsdl',        // namespace 
     'urn:RectangleAreawsdl#RectangleArea',   // soapaction 
     'rpc',           // style 
     'encoded',          // use 
     '2=> : Calculate a rectangle area as (L*l)'   // documentation 
    ); 


    // Register the RectangleArea method to expose 
    $server->register('get_message',     // method name 
     array('nm' => 'xsd:string'),  // input parameters 
     array('area_r' => 'xsd:string'),    // output parameters 
     'urn:mathwsdl',        // namespace 
     'urn:get_messagewsdl#get_message',   // soapaction 
     'rpc',           // style 
     'encoded',          // use 
     '3=> : Print a Message as name'   // documentation 
    ); 




if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA =file_get_contents('php://input'); 
$server->service($HTTP_RAW_POST_DATA); 
// create HTTP listener 
//$server->service($HTTP_RAW_POST_DATA); 
exit(); 
?> 

之後創建client.php

<?php 
require_once ('lib/nusoap.php'); 
//Give it value at parameter 
$param = array('your_name' => 'Monotosh Roy'); 
//Create object that referer a web services 
$client = new soapclient('http://localhost:81/WebServiceSOAP/server.php?wsdl', true); 

// Check for an error 
    $err = $client->getError(); 
    if ($err) { 
     // Display the error 
     echo '<h2>Constructor error</h2><pre>' . $err . '</pre>'; 
     // At this point, you know any calls to 
     // this web service's methods will fail 
    } 


    // Call the TriangleArea SOAP method 
    $result = $client->call('TriangleArea', 
     array('b' => 10, 'h' => 15)); 

    // Check for a fault 
    if ($client->fault) { 
     echo '<h2>Fault</h2><pre>'; 
     print_r($result); 
     echo '</pre>'; 
    } else { 
     // Check for errors 
     $err = $client->getError(); 
     if ($err) { 
      // Display the error 
      echo '<h2>Error</h2><pre>' . $err . '</pre>'; 
     } else { 
      // Display the result 
      echo '<h2>Result</h2><pre>'; 
      print_r($result); 
     echo '</pre>'; 
     } 
    } 
    // Call the RectangleArea SOAP method 
    $result = $client->call('RectangleArea', 
     array('L' => 40, 'l' => 20)); 

    // Check for a fault 
    if ($client->fault) { 
     echo '<h2>Fault</h2><pre>'; 
     print_r($result); 
     echo '</pre>'; 
    } else { 
     // Check for errors 
     $err = $client->getError(); 
     if ($err) { 
      // Display the error 
      echo '<h2>Error</h2><pre>' . $err . '</pre>'; 
     } else { 
      // Display the result 
      echo '<h2>Result</h2><pre>'; 
      print_r($result); 
     echo '</pre>'; 
     } 
    } 

    // Display the request and response 
    /* echo '<h2>Request</h2>'; 
    echo '<pre>' . htmlspecialchars($client->request, 
     ENT_QUOTES) . '</pre>'; 
    echo '<h2>Response</h2>'; 
    echo '<pre>' . htmlspecialchars($client->response, 
     ENT_QUOTES) . '</pre>';*/ 

//Call a function at server and send parameters too 
$response = $client->call('get_message',$param); 
//Process result 
if($client->fault) 
{ 
echo "<h2>FAULT:</h2> <p>Code: (".$client->faultcode."</p>"; 
echo "String: ".$client->faultstring; 
} 
else 
{ 
echo $response; 
} 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
     <meta http-equiv="content-type" content="text/html;charset=UTF-8"> 
     <title>Web Service SOAP and AJAX</title>   
    </head> 
    <script type="text/javascript" src="ajaxSOAP.js"></script> 
    <body>  
     <div style="position:relative;left:0px; 
     top:-12px;background-color:#1D3968;margin:0px;"> 
     <h2 align="center"><font color="#ffffff"> 
     Consume WebServices through SOAP-AJAX calls</font></h2></div> 
     <table align="center" cellpading="0px" cellspacing="3px" 
     bordercolor="#000000" border="0" 
     style="position:relative;width:300px;height:200px;"> 
     <tr> 
      <td colspan="2" align="center"><h1>Rectangle Area</h1></td> 
     </tr> 
     <tr> 
      <td valign="center"><font color="#cc0000" size="3"> 
      Insert value for l:</font></td> 
      <td><input id="l_id" type="text"></td> 
     </tr> 
     <tr> 
      <td><font color="#cc0000" size="3">Insert value for L:</font></td> 
      <td><input id="L_id" type="text"></td> 
     </tr> 
     <tr> 
      <td><input type="button" value="Calculate Area" onclick="myAjax();"></td> 
     </tr> 
     <tr> 
      <td colspan="2"> 
      <div id="resultDiv"></div> 
      </td> 
     </tr> 
     </table>  
    </body> 
    </html> 

ajaxSOAP.js文件包含

var xhrTimeout=100; 

function myAjax(){ 
var l_var = document.getElementById("l_id").value; 
var L_var = document.getElementById("L_id").value; 

var soapMessage ='<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:mathwsdl"> <SOAP-ENV:Body><tns:RectangleArea xmlns:tns="urn:mathwsdl"><L xsi:type="xsd:int">'+L_var+'</L><l xsi:type="xsd:int">'+l_var+'</l></tns:RectangleArea></SOAP-ENV:Body></SOAP-ENV:Envelope>'; 

var url='http://localhost:81/WebServiceSOAP/server.php'; 
if(window.XMLHttpRequest) { 
     httpRequest=new XMLHttpRequest(); 
    } 
    else if (window.ActiveXObject) { 
     httpRequest=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    httpRequest.open("POST",url,true); 
    if (httpRequest.overrideMimeType) { 
     httpRequest.overrideMimeType("text/xml"); 
    } 
    httpRequest.onreadystatechange=callbackAjax; 

    httpRequest.setRequestHeader("Man","POST http://localhost:81/WebServiceSOAP/server.php HTTP/1.1")  

    httpRequest.setRequestHeader("MessageType", "CALL"); 

    httpRequest.setRequestHeader("Content-Type", "text/xml"); 

    httpRequest.send(soapMessage); 
} 

    function callbackAjax(){ 
     try { 
     if(httpRequest.readyState==4) { 
      if(httpRequest.status==200) { 
       clearTimeout(xhrTimeout);                
       resultDiv=document.getElementById("resultDiv");    
       resultDiv.style.display='inline';           
       resultDiv.innerHTML='<font color="#cc0000" size="4"><b>'+httpRequest.responseText+'</b></font>'; 
      } 
     } 
     } catch(e) { 
      alert("Error!"+e); 
     }  
    }