简体   繁体   English

将 JQuery AJAX 请求转换为 cURL 或原生 PHP

[英]Converting a JQuery AJAX request to cURL or native PHP

I have the following jquery AJAX code that works fine with my server.我有以下 jquery AJAX 代码,可以在我的服务器上正常工作。

                $.ajax({
                type: "POST",
                url: "myserverthing.php",
                data: {time: timestamp,
                       prog: progName,
                       qual: qualifier,
                       level: lvl, 
                       msg: message 
                }
            });

I need to convert it either to cURL or native PHP.我需要将其转换为 cURL 或本机 PHP。

Assume all of the variables exist, are strings, and contain a value which may contain special characters.假设所有变量都存在,都是字符串,并且包含一个可能包含特殊字符的值。

There is no response offered by or expected from the server.服务器没有提供或预期的响应。

OK, let's play your way.好吧,让我们按照你的方式玩吧。

So far after some significant research along several avenues, what I came up with is this:到目前为止,在沿着几个途径进行了一些重要的研究之后,我想出了这个:

       $url = "myserverthing.php";
    $fields = array(
                    'time'=>urlencode($time),
                    'prog'=>urlencode($progName),
                    'qual'=>urlencode($qual),
                    'level'=>urlencode($type),
                    'msg'=>urlencode($message)
                    );

    //url-ify the data for the POST
    $fields_string = "";

    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, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //execute post
    curl_exec($ch);

And what happens is "nothing", the server doesn't seem to "see" the request.发生的事情是“什么都没有”,服务器似乎没有“看到”请求。

But the first line of the server code is not executed as it is when I make the AJAX request.但是服务器代码的第一行没有像我发出 AJAX 请求时那样执行。

That first line of code writes the output of a print_r of the REQUEST to a file.第一行代码将 REQUEST 的 print_r 的输出写入文件。 That output is written when the AJAX access is made but not for the cURL access.该输出在进行 AJAX 访问时写入,但不用于 cURL 访问。

Again, any thoughts?再次,有什么想法吗?

Regards, Jim问候, 吉姆

OK i'm here to help好的,我是来帮忙的

<?php


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://linktofile.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "value1=data1&value2=data2");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);
//The output store in $server_output

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM