2014-09-17 17:39

JS和PHP - 从js发出信号后加载php数据而不发送回发

Alright so basically I have a flash login, which I handled to work with JS using ExternalInterface. I want the php to load only when the user has logged in, how is it possible to do this without sending a new postback (reloading the page)?

What I basically want is: the JS already appears once the user has logged in. I want it once clicked to execute a MySql query, get the data and show the user without reloading the page.

I know that's AJAX but I really don't know how to do it - I'm not familiar with php, I also don't know how I can run the php when a function is called in JS.

Best regards, iMix

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dsm17496 dsm17496 7年前

    You can use jquery, it would be a quick and practical solution.

    function login(){
        type: "POST",
        url: "your_login_script.php",
        data: { username: "thatuser", password: "thatpwd" }
      }).done(function( result ) {
    点赞 评论 复制链接分享
  • donglu9872 donglu9872 7年前

    Yes, you need to use AJAX.

    Here is an outline of the simplest procedure:

    1. Send a request to the server to run the PHP script in the background, without reloading the current web page.
    2. The PHP script will do the required query and format the result as HTML. It should not generate a whole page ... just a DIV or a TABLE tag with the data you want.
    3. Your Javascript will receive the HTML fragment and insert it into the current page.

    Here is the barest, most essential code to get the job done.

    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    xmlhttp.open("GET", "somescript.php", true);

    You should read up some on AJAX if you're going to put anything into public production. I also highly recommend using jQuery or one of the other Javascript libraries. They have much better abstractions for this kind of thing than anything you're likely to cook up yourself.

    点赞 评论 复制链接分享
  • douzhantao2857 douzhantao2857 7年前

    You'll want to make an XMLHttpRequest to another php file which returns the data. Then, with JS, parse the data from whatever format you returned it in (I recommend JSON), and update the HTML.

    Since you'll want the data only to be returned if the user is logged in, you probably want to send the username/password over an encrypted connection, in the body of a post request, then check in the php file if they're valid.

    点赞 评论 复制链接分享