2012-09-19 18 views
0

我希望能够完成我在PHP中使用AJAX完成AJAX所做的同样的事情。这可能吗?完成和AJAX一样只使用PHP

例如,请考虑下面的代码:

$.ajax({ 
     async: false, 
     url: "/path/to/script/script.php", 
     type: "post", 
     data: { 
      'arg1':'arg_val', 
      'oper':'get_data', 
      'arg2':'arg_val_2', 
      'id_number':'223' 
     }, 
     dataType: 'json', 
     success: function(data){ 
      est_data = data[0]; 
     }, 
     error: function(jqXHR, textStatus, errorThrown){ 
      return jqXHR['responseText']; 
     } 
    }); 

PHP内我想做同样的事情:通过几个职位变量的script.php,并使其返回字符串响应,这是我在得到success函数在上面的代码中。

我做了一些研究,我想我应该能够做到这一点使用http_post_fields,但我得到这样的响应:

HTTP/1.1 200 OK日期:星期三,2012年9月19日15:42: 01 GMT服务器:Apache/2.2.20(Ubuntu)X- Powered By:PHP/5.3.6-13ubuntu3.9 Set-Cookie: 53f143479d91e79747661fcf2777a0fa = 5kidtm7rcdn14o33amljgg8922; path =/ Vary:Accept-Encoding Content-Length:15 Content-Type:text/html not authorized。

任何人都知道如何做到这一点?

谢谢!

+0

确保您发送的内容类型为文本/ JSON –

+0

从你得到的回应来看,(“未授权”的结尾),它看起来像有一些授权步骤你错过了。有没有一个会议或什么? – Crontab

回答

1

是的,您需要在stream_context_create()的帮助下使用file_get_contents()。您也可以使用curl

下面是使用的file_get_contents一个例子:

$options = array(
    'http'=>array(
    'method'=>"POST", 
    'header'=> 
     "Accept-language: en\r\n". 
     "Content-type: application/x-www-form-urlencoded\r\n", 
    'content'=>http_build_query(
     array(
      'arg1'=>'arg_val', 
      'oper'=>'get_data', 
      'arg2'=>'arg_val_2', 
      'id_number'=>'223' 
     ),'','&' 
    ) 
)); 
$context = stream_context_create($options); 
$refno = file_get_contents('/path/to/script/script.php',false,$context); 
$refno = json_decode($refno, true); 
var_dump($refno); // juse use $refno as an array. 
+0

它似乎只是返回一个集合长字符串,其中包含了很多'script.php'的代码内容。脚本应该返回JSON字符串,是否需要更改'Content-type'选项? –

+0

是的,这个方法只是返回php脚本的内容(目标URL),并没有真正执行脚本。它只是获取代码内容。任何ides为什么? –

2

我认为在这种情况下,curl会是你最好的朋友。您可以使用它发送POST请求并发送数据,模拟正在提交的表单。

结账this post

$url = 'http://example.com/request.php'; 
$fields = array(
      'username' => urlencode($last_name), 
      'password' => urlencode($first_name), 
     ); 

//url-ify the data for the POST 
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } 
rtrim($fields_string, '&'); 

//open connection 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_URL, $url); 
curl_setopt($ch,CURLOPT_POST, count($fields)); 
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 

//execute post 
$result = curl_exec($ch); 

//close connection 
curl_close($ch); 
+0

我已经取代了我的URL,但服务器脚本永远不会被调用...我也发现这篇文章:http://stackoverflow.com/questions/5412069/can-i-do-a-curl-request-to-the-同一服务器。这表明在您自己的服务器上对脚本使用curl可能很难或不正确。 –

1

当然你可以做到这一点。您只需使用PHP库(例如curl)将POST发送到脚本。关于AJAX没有什么特别之处,它只是用Javascript编写的。最后,这只是一个HTTP响应/请求。