English 中文(简体)
How to emulate XMLHttpRequest client using PHP?
原标题:

I m looking for an example how to emulate XMLHttpRequest client using PHP.

In other words, send the request over HTTP POST message, and receive and process the callback message.

最佳回答

server.php:

<?php var_dump($_POST);

client.html:

<html>
 <head>
  <title>omg</title>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
  $(document).ready(function () {
      $.post(
          "server.php"
        , {omg: "wtf"}
        , function (data) { alert(data); }
      );
  });
  </script>
 </head>
 <body></body>
</html>

edit: ok, so it s http client written in PHP!

<?php

$r = new HTTPRequest("server.php", HTTP_METH_POST);
$r->addPostFields(array( omg  =>  wtf ));
$r->send();
var_dump($r->getResponseCode());
var_dump($r->getResponseBody()); 
问题回答

If you want to really simulate an AJAX request, you should, together with all of the above solutions, consider sending this header with your request:

X-Requested-With: XMLHttpRequest

(check the manuals to the solutions how to set custom headers). Prototype, jQuery, mootools and the such all send this header when they request data via AJAX.

you can use curl for that purpose

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// set the post 
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,array(  foo  =>  bar ));

// grab URL and pass it to the browser
$result = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
var_dump($result);

The easiest method would be the command line tool curl, especially if you have a sample of the data you want to post.





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签