在没有页面刷新的情况下将变量从JavaScript传递到PHP [重复]

在没有页面刷新的情况下将变量从JavaScript传递到PHP [重复]

问题描述:

This question already has an answer here:

I'm writing some code that has a variable in JavaScript that must be passed into the PHP script in the same document. The user input will be used to be scraped from some external site.

The JavaScript variable is HtmlLink, and it needs to be passed to the PHP code where it says INSERT HTMLLINK VARIABLE HERE without reloading the page.

<!DOCTYPE HTML>
<HEAD>
   <TITLE>Test Input</TITLE>
   <SCRIPT>
      type = "text/javascript"
      function testResults (form) {
         var TestVar = form.inputbox.value + ".html";
         var HtmlLink = "www.mp3skull.com/mp3/" + TestVar;
         document.write(HtmlLink);
      }
   </SCRIPT>
   <?php
      $contents = file_get_contents('INSERT HTMLLINK VARIABLE HERE');
      $dom = new DOMDocument();
      libxml_use_internal_errors(true);
      $dom->loadHTML($contents);
      libxml_clear_errors();
      $xpath = new DOMXpath($dom);

      $element = $xpath->query('//div[@id="right_song"]/div[3]/div[1]/div[1]/a')->item(0)-                    
      echo $element;  
   ?>  
</HEAD>
<BODY>
   <FORM NAME="myform" ACTION="" METHOD="GET"> Song Name <BR>
      <INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
      <INPUT TYPE="button" NAME="button" Value="Search" onClick="testResults(this.form)">
   </FORM>
</BODY>
</HTML>
</div>

此问题已经存在 这里有一个答案: p>

  • 将javascript变量传递给php而不刷新页面 2 answers span> li> ul> div>

    我正在编写一些在JavaScript中具有变量的代码 必须传递到同一文档中的PHP脚本中。 用户输入将用于从某个外部站点中删除。 p>

    JavaScript变量是 HtmlLink code>,需要将其传递给PHP代码,在那里它 在没有重新加载页面的情况下 INSERT HTMLLINK VARIABLE HERE code>。 p>

     &lt;!DOCTYPE HTML&gt; 
    &lt; HEAD&gt; 
    &lt; TITLE&gt;测试输入&lt;  ; / TITLE&gt; 
    &lt; SCRIPT&gt; 
     type =“text / javascript”
     function testResults(form){
     var TestVar = form.inputbox.value +“。html”; 
     var HtmlLink =“www  .mp3skull.com / mp3 /“+ TestVar; 
     document.write(HtmlLink); 
    } 
    &lt; / SCRIPT&gt; 
    &lt;?php 
     $ contents = file_get_contents('INSERT HTMLLINK VARIABLE HERE')  ; 
     $ dom = new DOMDocument(); 
     libxml_use_internal_errors(true); 
     $ dom-&gt; loadHTML($ contents); 
     libxml_clear_errors(); 
     $ xpath = new DOMXpath($ dom); \  n 
     $ element = $ xpath-&gt; query('// div [@ id =“right_song”] / div [3] / div [1] / div [1] / a') - &gt; item(0  ) -  
      echo $ element;  
    ?&gt;  
    &lt; / HEAD&gt; 
    &lt; BODY&gt; 
    &lt; FORM NAME =“myform”ACTION =“”METHOD =“GET”&gt; 歌曲名称&lt; BR&gt; 
    &lt; INPUT TYPE =“text”NAME =“inputbox”VALUE =“”&gt;&lt; P&gt; 
    &lt; INPUT TYPE =“button”NAME =“button”Value =“Search  “onClick =”testResults(this.form)“&gt; 
    &lt; / FORM&gt; 
    &lt; / BODY&gt; 
    &lt; / HTML&gt; 
      code>  pre> 
      div>

If you want to do some searching, first of course build the proper URL first, then from there search/scrape the site, actually the base code is already working so its time to build on that. You can do something like this: Sample Demo

$main_url = 'http://www.mp3skull.com/mp3/';
$results = array();

if(isset($_POST['submit'])) {
    // handle input (sample: hot mallets)
    $input = preg_replace('/[\s]+/', '_', strtolower(trim($_POST['input'])));
    $main_url .= $input . '.html'; // turns to hot_mallets.html

    $contents = @file_get_contents($main_url);
    if($contents !== false) { // simple error checking

        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($contents);
        libxml_clear_errors();
        $xpath = new DOMXpath($dom);

        $search_results = $xpath->query('//div[@id="song_html"]');
        if($search_results->length > 0) {
            foreach($search_results as $result) {
                // each row result, put it inside the array
                $results[] = $xpath->query('//div[@id="right_song"]/div[3]/div[1]/div[1]/a', $result)->item(0)->getAttribute('href');
            }
        } else {
            echo 'Zero results';
        }


    } else {
        echo 'Some error on getting results from external site.';
        exit;
    }
}

?>

<form method="POST">
    <label for="inputbox">Song Name: <input type="text" id="inputbox" name="input"/ ></label>
    <input type="submit" name="submit" />
</form>
<?php if(!empty($results)): ?>
<h3>Search Results:</h3>
<ul>
    <?php foreach($results as $result): ?>
        <li><?php echo $result; ?></li>
    <?php endforeach; ?>
</ul>
<?php endif; ?>

Because of the way that pages are loaded on the web this doesn't really make sense in most setups. The PHP runs on the server, sends the javascript and HTML to the client and then the javascript executes on the client. At that point in the process it's too late for javascript to set a variable in php because php is already finished loading. You could use ajax to send the request from javascript. If you did that the page would load like this:

(Server gives initial HTML/javascript/CSS to client)->(Client runs javascript which makes request to server (after the user has entered the data))->(Result of external request returns and is now usable by javascript).

You don't really need to do that for what you're trying to do though - fetch a link off of another page. What you should really do is write your javascript stuff in php and then echo out the link. Then, set the form to submit back to the same page. Here's an example:

<!doctype html>
<head>
    <title>Fetch Link</title>
</head>
    <body>
        <?php
            ini_set('display_errors', 0);
            if (isset ($_GET['search_term']))
            {
                $searchTerm = $_GET['search_term'];
                $searchPage = "http://www.example.com/".$searchTerm.'.html';
                $searchPageContents = file_get_contents($searchPage);
                $feedBack = '';
                $failedMessage = 'Sorry, we couldn\'t match your search =(';

                if ($searchPageContents !== FALSE)
                {
                    $searchPageDom = new DOMDocument();

                    if (!$searchPageDom->loadHTML($searchPageContents))
                        $feedBack = $failedMessage;
                    else
                    {
                        $searchPageXpathWrapper = new DOMXpath($searchPageDom);
                        $searchLinkNode = $searchPageXpathWrapper
                        ->query('SOME QUERY HERE')
                        ->item(0);

                        $searchLink = $searchPageDom->saveHTML ($searchLinkNode);
                        $feedBack = $searchLink;
                    }
                }
                else
                    $feedBack = $failedMessage;

            }
            else
                $feedBack = 'Please enter a search term';

            echo $feedBack.'<br>';
        ?>
        <form name="myform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="GET">
            <label for='search_name' for='search_term'>Search Term</label>
            <input type="text" name="search_term">
            <input type='submit' value='Search'>
        </form>
    </body>
</html>

Of course, unless you have a particularly good reason to be fetching the link from the page instead of just generating the link yourself - you can generate the link yourself with minimal javascript and save the round trip to the server and guard against the possibility of the page formatting changing on the other side.