我希望能够完成与在PHP中使用AJAX使用JS所做的相同的事情。这个是可能的吗?
例如,考虑以下代码:
$.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内部,我想做同样的事情:将几个post变量传递给script.php,并让它返回字符串响应,这是我在上面代码中的success函数中得到的。
我做了一些研究,我想我应该可以用字段来做这件事,但是我得到了这样的回应:
HTTP/1.1 200确定日期: 19,2012年9月19日15:42:01 GMT Server: Apache/2.2.20 (Ubuntu) X驱动-By:PHP/5.3.6-13 ubuntu3.9 Set-Cookie: 53f143479d91e79747661fcf2777a0fa=5kidtm7rcdn14o33amljgg8922;path=/ Vary:接受-编码内容-长度: 15内容-类型:文本/html未授权。
有人知道怎么做吗?
谢谢!!
发布于 2012-09-19 16:02:00
是的,您需要在内容()的帮助下使用创建()。您也可以使用卷曲。
下面是一个使用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.发布于 2012-09-19 15:58:48
我想在这件事上卷发会是你最好的朋友。您可以使用它来发布请求并发送数据,模拟正在提交的表单。
看看这个职位。
$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);发布于 2012-09-19 15:58:54
你当然能做到。您所需要做的就是使用PHP库(例如curl)向脚本发送一个帖子。AJAX没有什么特别之处,它只是用Javascript编写的。最后,它只是一个HTTP响应/请求。
https://stackoverflow.com/questions/12498461
复制相似问题