【发布时间】:2019-09-28 03:39:11
【问题描述】:
我正在尝试通过 AJAX 向黑猩猩邮件帐户发布一段。如果调用成功,我想重定向到一个 URL。经过多次测试,每次调用都是成功的,但我无法获得重定向......就好像代码运行然后跳过 if “result = success”,然后直接进入我的 else 语句,这只是一个警报。当我查看返回的数据时,我得到“nullsuccess”。我什至尝试过 if result = "nullsuccess" 并且它仍然适用于 else 语句。
$("#mc-embedded-subscribe-form").submit(function(e) {
var url = $(this).prop('action'); // the script where you handle the form input.
$.ajax({
type: "POST",
url: "update-member.php",
data: $("#mc-embedded-subscribe-form").serialize(), // serializes the form's elements.
dataType: "text",
success: function(data){
if(data.result == 'success'){
window.location.href = 'https://google.com';
}else{
alert("ERROR-ONLY IT STILL SUBMITS DATA!");
}
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
以上数据类型 - 我使用了“文本”,因为如果我使用“json”或“jsonp”,它会完全忽略成功函数,包括 if 和 else 语句。有趣的是这三种数据类型仍然可以成功发布数据。
这里是 PHP(update-member.php)
$apikey = 'myAPIKEYHERE';
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $_POST['email_address'],
'status' => 'subscribed',
'merge_fields' => array(
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'MYMAILCHIMPURL');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
echo json_encode($response_array);
$result = curl_exec($ch);
$message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
echo $message; //echos nullsuccess
我觉得我没有从 update-member.php 返回一些东西,或者我没有在我的 ajax 成功函数中正确收集它。
【问题讨论】:
-
从 json_ecode($response_array) 中移除回显
-
在您的网络选项卡中检查响应,我认为您获得的不仅仅是成功
-
正如@AhmedSunny 指出的,您的PHP 是
echoing 2 件事-echo json_encode($response_array);和后来的echo $message;。所以你会得到 2 个连接的字符串,这就解释了nullsuccess。 -
好的,所以我已经注释掉了除了 $message 之外的所有其他内容...返回成功。但是我在 ajax 脚本中的成功函数应该是什么样子?它仍然会跳过 if 成功并转到 else 警报。
-
@RyanRyan 我添加了答案。
标签: jquery ajax mailchimp php-curl forms http-post