为什么我在从我的服务器发出的 ajax 调用中得到额外的数据作为响应?

Why I am I getting additional data as response back in my ajax call from my server?

这是我的代码

$url = 'https://'.$_ENV["MAIL_CHIMP_DC"] .'.api.mailchimp.com/3.0/lists/'.$_ENV["MAIL_CHIMP_LIST_ID"].'/members';
    error_log('url-mail_chimp');
    error_log($url);
    $authorization_header=base64_encode('anystring:'.$_ENV['MAIL_CHIMP_API_KEY']);
    error_log($authorization_header);
    $ch=curl_init($url);
    $data_string = $data;
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Basic '.$authorization_header));
    $result =curl_exec($ch);
    error_log($result);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    error_log($httpcode);
    curl_close($ch);
    echo 'hello';

这一切都在 ajax 调用中调用的控制器中。但是当我在 jquery success 处理程序上执行 console.log(data) 时,我得到了由 curl 请求发送的完整响应,并且 "hello" 也附加到该响应。我不知道响应是如何发送的。

您的 curl 调用缺少 CURLOPT_RETURNTRANSFER 选项。如果没有这个,curl_exec 将不会 return 调用的响应作为字符串,而是直接输出。来自 manual for CURLOPT_RETURNTRANSFER:

TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.

所以,添加

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

添加到您的代码中,输出应该正确地 return 编辑到您的 $result 变量中。