2016-06-13 12 views
1

私は歌詞アップロードフォームのライブ検索をコーディングしています。私はAJAX呼び出しを行う予定の小さなスクリプトを作成しました。 artistalbum、およびsongレコードを返します。出力JSONはJSで使用されます。php変数へのPHPファイル出力の割り当て/エコー

// get_records.php 

include_once("connect2db.php"); 

if (empty($_GET)) { 
    $artists = json_encode(mysqli_fetch_all($mysqli->query("SELECT artist from `artists`"), MYSQLI_ASSOC)); 
    echo $artists; 
} else { 
    if (isset($_GET["artist"])) { 
     $artist = test_input($_GET["artist"]); 
     if (isset($_GET["album"])) { 
      // ... 
      echo $songs; 
     } else { 
      // ... 
      echo $albums; 
     } 
    } 
} 

$mysqli->close(); 

かなり簡単です。 3例のために設計されている:フォームページで

  • get_records.php // returns artists
  • get_records.php?artist=XXX // returns albums of XXX
  • get_records.php?artist=XXX&album=YYY // returns songs from the album YYY that belongs to XXX

、私はartistsはすでに任意の入力前にJS変数にassingedことにしたいです。私はそれのためにAJAXを使いたくありません。私がそれを動作させる1つの方法は次のようなものです:

<?php 
    echo "var artists = "; 
    include("get_records.php"); 
    echo ";"; 
?> 

これはちょっと間違っているようです。 PHPファイルの出力を、あなたが知っているこの

<?php 
    echo "var artists = " . get_output("get_records.php") . ";"; 
?> 

のようにそれを行う取得する方法はありません、それはコンテンツだ、ありますか?

+1

方法。 file_get_contents( "http://localhost/get_records.php")。 ";"; '? – revo

+0

@revoすでにそれを試しました。これは、ファイルの内容を読み取って文字列として返します。ファイル内でコードを実行しません。 – akinuri

+1

これはphpファイルの中にそれを含めているので、正常に動作するはずです。出力はPHPコードの内容ではなく出力になります。 –

答えて

0

これは、コードを関数内に配置し、必要に応じて他のスクリプトから呼び出すことで実行できます。

メインスクリプト:

<?php 

// get_records.php 

function execute() 
{ 
    // get_records.php 

    include_once("connect2db.php"); 

    if (empty($_GET)) { 
     $artists = json_encode(mysqli_fetch_all($mysqli->query("SELECT artist from `artists`"), MYSQLI_ASSOC)); 
     $response = $artists; 
    } else { 
     if (isset($_GET["artist"])) { 
      $artist = test_input($_GET["artist"]); 
      if (isset($_GET["album"])) { 
       // ... 
       $response = $songs; 
      } else { 
       // ... 
       $response = $albums; 
      } 
     } 
    } 

    $mysqli->close(); 

    return $response; 
} 

Ajaxのスクリプト: `エコー "のvarアーティスト=" について

<?php 
// ajax_script.php 

include_once("get_records.php"); 

echo execute(); 

フォームスクリプト

<?php 

// Form File - form_file.php 
include_once("get_records.php"); 

$content = execute(); 

$response = "<script> var artists = $content ; </script>"; 

echo $response; 
関連する問題