weixin_33716154 2017-08-16 15:36 采纳率: 0%
浏览 28

ajax无法正常工作

What I miss?

1.php:

<button id = "testtext">Show</button>
<script src="jquery-3.1.1.min.js"></script>
<script src="js.js"></script>

js.js:

$("#testtext").bind("click", previewNewShortnameFunc);
function previewNewShortnameFunc() {
    var lalalatext = "lalala";
    var lalalaint = 100;
    console.log("sent: " + lalalatext + " and " + lalalaint);
    $.ajax ({
        url: "testprint4.php",
        type: "POST",
        data : {str: lalalatext, int: lalalaint},
        success: function(data) {
            window.open("testprint4.php");
        }
    });
}

testprint4.php

<?php
$str = $_POST['str'];
$int = $_POST['int'];
echo $str;
echo $int;
?>

I see blank page instead of lalala100. What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • weixin_33737774 2017-08-16 15:38
    关注

    This code includes two separate HTTP requests. You are first doing an Ajax request getting that response prior to redirecting user to request same script w/o any parameter, thus resulting in empty page.

    $.ajax ({
        url: "testprint4.php",
        type: "POST",
        data : {str: lalalatext, int: lalalaint},
        success: function(data) {
    
        }
    });
    

    This part makes browser requesting the script with provided data as POST. When the response has been received it is available in data of callback linked with success-property. The request is finished then.

    Instead of processing that response with your expected content you use

    window.open("testprint4.php");
    

    to open new window of browser for requesting same script again, this time using GET request w/o any argument. Therefore you will see a blank page.

    评论

报告相同问题?