PHP / jQuery/AJAX +带身份验证的 POST SOAP 请求

发布于 2024-11-30 09:40:47 字数 407 浏览 0 评论 0原文

我正在寻找使用 jQuery/AJAX 通过 SOAP 执行表单(发布)请求的方法。

我找到了以下具有 ColdFusion 背景的 jQuery/AJAX SOAP 请求解决方案。

使用 jQuery 发布 XML SOAP 请求

有人知道如何用 PHP 实现它吗?

请注意:

  • 需要 ssl 连接,需要
  • 肥皂身份验证(用户和密码)。

非常感谢任何帮助/建议。

I was looking for way to perform form (post) request with SOAP using jQuery/AJAX.

I have found following solution for jQuery/AJAX SOAP request with ColdFusion background.

Posting XML SOAP Requests With jQuery

Anyone know how to implement that with PHP?

Please note:

  • ssl connection will be required
  • soap authentication(user & pass) will be required.

Any help/suggestion much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

请持续率性 2024-12-07 09:40:47

我知道这是旧的......但我遇到了这个确切的问题(我在他拥有的链接上使用代理,并且在工作中移动到新系统时我需要在 php 中使用代理。)

如果有人感兴趣,我翻译了他们的Coldfusion 代理转换为近似的 php 等效项(没有错误检查,但 jquery ajax 调用是相同的,除了 php 文件)

<?php 
    $action = $_SERVER['HTTP_SOAPACTION'];
    $target = $_SERVER['HTTP_SOAPTARGET'];
    $soap_body = file_get_contents('php://input');

    $headers = array(
        "Content-type: text/xml;charset=\"utf-8\"",
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: ".$action,
        "Content-length: ".strlen($soap_body),
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $target);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $soap_body);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch); 
    curl_close($ch);
    echo($response);
?>

这里又是一个链接,可以查看调用此代理所需的 html 和 javascript/jquery。 http://www.bennadel.com/blog /1853-Posting-XML-SOAP-Requests-With-jQuery.htm

I know this is old... but I ran into this exact problem (I was using the proxy on the link he has and I needed one in php when moving to a new system at work.)

If anyone is interested, I translated their coldfusion proxy into an approximate php equivalent (no error checking, but the jquery ajax call is identical, except to a php file)

<?php 
    $action = $_SERVER['HTTP_SOAPACTION'];
    $target = $_SERVER['HTTP_SOAPTARGET'];
    $soap_body = file_get_contents('php://input');

    $headers = array(
        "Content-type: text/xml;charset=\"utf-8\"",
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: ".$action,
        "Content-length: ".strlen($soap_body),
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $target);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $soap_body);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch); 
    curl_close($ch);
    echo($response);
?>

Here is a link again to see the html and javascript/jquery required for calling this proxy. http://www.bennadel.com/blog/1853-Posting-XML-SOAP-Requests-With-jQuery.htm

若无相欠,怎会相见 2024-12-07 09:40:47

SOAP 请求示例:

  • 使用 HTTPS / SSL,
  • 并通过密码和用户名身份验证
  • 进行测试并正常工作!
  • 两个回显示例 - 用于单个和多个结果

     <?php 
        //Data, connection, auth
        $dataFromTheForm = $_POST['fieldName']; // request data from the form
        $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
        $soapUser = "username";  //  username
        $soapPassword = "password"; // password

        // xml post structure

        $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                              <soap:Body>
                                <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your's WSDL URL
                                  <PRICE>'.$dataFromTheForm.'</PRICE> // data from the form, e.g. some ID number
                                </GetItemPrice >
                              </soap:Body>
                            </soap:Envelope>';

            $headers = array(
                        "Content-type: text/xml;charset=\"utf-8\"",
                        "Accept: text/xml",
                        "Cache-Control: no-cache",
                        "Pragma: no-cache",
                        "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", // your op URL
                        "Content-length: ".strlen($xml_post_string),
                    );

            $url = $soapUrl;

            // PHP cURL  for https connection with auth
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // XML REQUEST
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // converting
            $response = curl_exec($ch); 
            curl_close($ch);

            // converting
            $response1 = str_replace("<soap:Body>","",$response);
            $response2 = str_replace("</soap:Body>","",$response1);

            // convertingc to XML
            $parser = simplexml_load_string($response2);        



    ?>

显示单个结果示例:

  $getPrice = $parser->GetItemPriceResponse->PRICE;

  if($getPrice) { // if found based on our $_POST entry echo the result
         echo $getPrice;
  } else { // if not found, echo error
        echo "Sorry. No price tag for this item.";
  }

显示多个结果示例:

 $getPrice = $parser->GetItemPriceResponse->PRICE;

                if($getPrice) { // if found  more than 0, return as a select dropdown

                    echo "<form action='soapMoreDetails.php' method='post'>";
                    echo "<select name='priceMoreDetails'>";

                    foreach ($parser->GetItemPriceResponse as $item) {
                        echo '<option value="'.$item->PRICE.'">';
                        echo $item->PriceBasedOnSize; // for e.g. different prices for different sizes
                        echo '</option>';
                    }

                    echo "</select>";
                    echo "<input type='submit'>";
                    echo "</form>";

                } else {
                    echo "Sorry. No records found.";

                }

SOAP request example:

  • with HTTPS / SSL
  • with password and username auth
  • tested and working!
  • two echo examples - for single and multiple results

     <?php 
        //Data, connection, auth
        $dataFromTheForm = $_POST['fieldName']; // request data from the form
        $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
        $soapUser = "username";  //  username
        $soapPassword = "password"; // password

        // xml post structure

        $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                              <soap:Body>
                                <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your's WSDL URL
                                  <PRICE>'.$dataFromTheForm.'</PRICE> // data from the form, e.g. some ID number
                                </GetItemPrice >
                              </soap:Body>
                            </soap:Envelope>';

            $headers = array(
                        "Content-type: text/xml;charset=\"utf-8\"",
                        "Accept: text/xml",
                        "Cache-Control: no-cache",
                        "Pragma: no-cache",
                        "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", // your op URL
                        "Content-length: ".strlen($xml_post_string),
                    );

            $url = $soapUrl;

            // PHP cURL  for https connection with auth
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // XML REQUEST
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // converting
            $response = curl_exec($ch); 
            curl_close($ch);

            // converting
            $response1 = str_replace("<soap:Body>","",$response);
            $response2 = str_replace("</soap:Body>","",$response1);

            // convertingc to XML
            $parser = simplexml_load_string($response2);        



    ?>

Displaying single result example:

  $getPrice = $parser->GetItemPriceResponse->PRICE;

  if($getPrice) { // if found based on our $_POST entry echo the result
         echo $getPrice;
  } else { // if not found, echo error
        echo "Sorry. No price tag for this item.";
  }

Displaying multiple results example:

 $getPrice = $parser->GetItemPriceResponse->PRICE;

                if($getPrice) { // if found  more than 0, return as a select dropdown

                    echo "<form action='soapMoreDetails.php' method='post'>";
                    echo "<select name='priceMoreDetails'>";

                    foreach ($parser->GetItemPriceResponse as $item) {
                        echo '<option value="'.$item->PRICE.'">';
                        echo $item->PriceBasedOnSize; // for e.g. different prices for different sizes
                        echo '</option>';
                    }

                    echo "</select>";
                    echo "<input type='submit'>";
                    echo "</form>";

                } else {
                    echo "Sorry. No records found.";

                }
九八野马 2024-12-07 09:40:47

我已经尝试使用ajax客户端使用SOAP PHP服务器,并找到工作代码

首先从此处下载nusoap库,

然后创建< strong>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); 
      }      
   }

I have tried SOAP PHP server with ajax client and found working code

First Download nusoap library from Here

then create 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(); 
?>

after that create 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 file contains

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); 
      }      
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文