javascript - 如何将ajax响应值传递到另一个页面?

标签 javascript php jquery ajax

我正在尝试向 PHP 文件发送 AJAX 响应。根据回复我想重定向到另一个页面。如果响应是成功,我想重定向到“谢谢”页面以及参数数据。

如何将这个 transactionId 传递到另一个页面?

if ($result->success) 
{
    print_r("success!: " .$result->transaction->id);
} 
else if ($result->transaction) {
    print_r("Error processing transaction:");
    print_r("\n  code: " .$result->transaction->processorResponseCode);
    print_r("\n  text: " .$result->transaction->processorResponseText);
}
else 
{
    print_r("Validation errors: \n");
    print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
    var serializedData = $(this).serialize();
    $.post('card.php', serializedData, function(response) {
        // Log the response to the console
        console.log("Response: "+response);
        alert(response);

        if (response == "success") {
            window.location.href = 'http://www.google.com';
        }
    });
});
});

最佳答案

更改你的 php 输出

if ($result->success) 
{
    print_r("success!: " .$result->transaction->id);
} 
else if ($result->transaction) {
    print_r("Error processing transaction:");
    print_r("\n  code: " .$result->transaction->processorResponseCode);
    print_r("\n  text: " .$result->transaction->processorResponseText);
}
else 
{
    print_r("Validation errors: \n");
    print_r($result->errors->deepAll());
}

if ($result->success) 
{
    echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
} 
else if ($result->transaction) {
    echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else 
{
   echo   json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));

}

并将你的js更改为以下内容

$('#paymentForm').submit(function() {
    var serializedData = $(this).serialize();
    $.post('card.php', serializedData, function(response) {
        // Log the response to the console
        console.log("Response: "+response);
        alert(response);
        var data= $.parseJSON(response);
        if (data.status == "success") {
            window.location.replace('http://www.google.com?id='+data.id)‌​;
        }else{
            alert('Operation Failed');
            if(data.code){
                console.log('response code: '+data.code);
            }
            console.log('response text: '+data.text);
        }
    });
});
});

关于javascript - 如何将ajax响应值传递到另一个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888965/

相关文章:

javascript - 如何使用 Enzyme 等待 Mocha 中 React 组件的完整渲染?

javascript - jQuery 忽略响应

javascript - 外部 javascript 加载但不执行

php - 将 .htaccess 翻译成 web.config

php - 使用ajax post请求发送两个数组

javascript - 使用 javascript 每 3 秒替换一个 div 的内容

php - 如何在不重新加载页面的情况下检查 PHP if 语句

php - 在 RecaptchaField.php 中找不到 SilverStripe 类 'SpamProtectorField'

javascript - 将 javascript 变量传递给 Rails Controller

javascript - 谷歌地图无法正常工作