用Jquery调用PHP [关闭]

I have a jquery file in which i have the following code:

var QUESTIONS = ["Q11", "Q22", "Q33", "Q44", "Q55"];
var ANSWERS = [["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"]];

Now i want to load the questions and answers from the PHP.

Trolling ahead!

If you want to load javascript into the PHP Userspace, you will need to lex and parse it, then read it into your own PHP userspace.

  1. Create a javascript lexer to read the content of the file
  2. From the token list, create a parser that will validate and construct and complex expression tree
  3. Then you can analyse the expression tree and extract the different values into model classes you will have created.

Or, you could simply, just copy the content over to PHP and use it normally!

You have three choices here.

Inline PHP

In the .PHP file that generates your web-page, directly write the text for your JavaScript arrays as if they were HTML or plain-text.

AJAX

Use an XMLHttpRequest object to call a separate a .PHP page that returns an XML response containing your entries. (You could also have it return JSON instead of XML.)

JSON-P

Have your PHP return JSON to a <script> tag, which gets automatically parsed and executed on the client. (usually as a single global variable.)

dataServer.php

$response = array();
$response['questions'] = array("Q11", "Q22", "Q33", "Q44", "Q55");
$response['answers'] = array(array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"));
print json_encode($response);

dataClient.js

$.ajax({
    url: "dataServer.php",
    dataType: "json",
    type: "GET",
    success: function(data, stat, xhr) {
        alert(data.questions.toSource());
        alert(data.answers.toSource());
    }
});