dongsonglian7303 2015-09-06 01:27
浏览 82

Javascript两个奇怪的问题:POST无法正常工作,window.location.href无效

I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening? Q1.

searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.

Q2 I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").

Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".

Thanks in advance!

 <html>
    <!-- google API reference -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <!-- my own script for search function -->

    <center>
    <form method="POST">
        <input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
        <div id="output">
        </div>
    </form>
    </center>   

      <!-- instant search function -->
 <script type="text/javascript">

function searchq(){
        // get the value
            var txt = $("input").val();
            // post the value
            if(txt){
                $.post("search.php", {searchVal: txt}, function(result){
                    $("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
                });
            }
            else{
                $("#search_output").html("");
            }


        };
function createq(){
    // allert for test purpose: test if the txt has got by the createq function
    alert(txt);
    **$.post( "create_object.php",{creatVal:txt} );**

}

// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
    if (evt.which == 13) {
       // find the first search result in DOM and trigger a click event 
        var redirectUrl = $('#search_output').find('a').first().attr('href');
        alert(redirectUrl);
      **window.location.href = "www.google.com";
window.location.href = "www.google.com";**
    }
})

</script>
    </html>

PHP file (search.php)

 <?php
if(isset($_POST["searchVal"])){
    //get the search
    $search=$_POST["searchVal"];
    //sort the search
    $search=preg_replace("#[^0-9a-z]#i","",$search);
    //query the search
    echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
    $query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
    $count=mysqli_num_rows($query);
    //sort the result
    if($count==0){
        $output="there was no search result";
    }
    else{
        while($row=mysqli_fetch_assoc($query)){

            $object_name=$row["name"];

            $output.="<div><a href='##'>".$object_name."</a></div>";
        }
    }
    echo $output;
}
?>

php file (create_object.php)

 <?php
    if(isset($_POST["createVal"])){
        $name=$_POST["createVal"];
        var_dump($name);

    }

?>
  • 写回答

2条回答 默认 最新

  • duanqiao0153 2015-09-06 01:36
    关注

    Try to bind the input with id

    var txt = $("input").val();
    
    <input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
    

    Change above to this

    var txt = $("#searchinput").val();
    
    <input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
    

    and I think you are trying to show the search result here

    <div id="output"></div>
    

    and the jQuery binding is this in your code

     $("#search_output").html("");
    

    So change the HTML to this

    <div id="search_output"></div>
    

    also this in our code

    $("#search").keypress(function(evt){
    

    there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this

        $("#searchinput").keypress(function(evt){
    

    The above change should also resolve the window.location.href not working problem

    So the HTML will be;

    <form method="POST">
        <input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
        <div id="search_output"></div>
    </form>
    

    and Script will be

    <script type="text/javascript">
    function searchq(){
        // get the value
        var txt = $("#searchinput").val();
        // post the value
        if(txt){
            $.post("search.php", {searchVal: txt}, function(result){
                $("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
            });
        }
        else{
            $("#search_output").html("");
        }
    }
    
    function createq(){
    // allert for test purpose: test if the txt has got by the createq function
        alert(txt);
        **$.post( "create_object.php",{creatVal:txt} );**
    }
    
    // if enter key pressed, redirect page to the first search result
    $("#searchinput").keypress(function(evt){
            if (evt.which == 13) {
            // find the first search result in DOM and trigger a click event 
            var redirectUrl = $('#search_output').find('a').first().attr('href');
            alert(redirectUrl);
            **window.location.href = "www.google.com";
            window.location.href = "www.google.com";**
        }
    });
    </script>
    

    Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.

    In the PHP, here

    if($count==0){
        $output="there was no search result";
    }
    else{
        while($row=mysqli_fetch_assoc($query)){
            $object_name=$row["name"];
            $output.="<div><a href='##'>".$object_name."</a></div>";
        }
    }
    

    $output. is wrong with dot, so change it to following

    if($count==0){
        $output="there was no search result";
    }
    else{
        while($row=mysqli_fetch_assoc($query)){
            $object_name=$row["name"];
            $output="<div><a href='#'>".$object_name."</a></div>";
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。