1

My PHP code is:

<?php
    class Sample{
    public $name = "N3mo";
    public $answer = "";
}
if(  isset( $_GET['request'] )  ){
    echo "Starting to read ";
    $req = $_GET[ 'request' ];
    $result = json_decode($req);
    if( $result->request == "Sample" ){
        $ans = new Sample();
        $ans->answer = " It Is Working !!! ";
        echo json_encode($ans);
    }else{
        echo "Not Supported";
    }
}
?>

Is there anything wrong

I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!

I tried using

$.getJSON('server.php',request={'request': 'Sample'}) )

but php can't read this input or it's wrong somehow

thank you

4

3 回答 3

1

试试这个。它使用 jQuery 从服务器 URL 加载内容输出

<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
          $("#button").click(function(event) {
              $('#responce').load('php_code.php?request={"request":"Sample"}');
          });
       });
   </script>
</head>
<body>
   <p>Click on the button to load results from php_code.php:</p>
   <div id="responce" style="background-color:yellow;padding:5px 15px">
          Waiting...
   </div>
   <input type="button" id="button" value="Load Data" />
</body>
</html>

下面的代码是您的代码的修改版本。存储在一个名为 php_code.php 的文件中,存储在与上述相同的目录中并进行测试。

<?php

class Sample
{
    public $name = "N3mo";
    public $answer = "";
}

if(  isset( $_GET['request'] )  )
{
    echo "Starting to read ";
    $req = $_GET['request'];
    $result = json_decode($req);

    if( isset($result->request) && $result->request == "Sample" )
    {
        $ans = new Sample();
        $ans->answer = " It Is Working !!! ";
        echo json_encode($ans);
    }
    else
    {
       echo "Not Supported";
    }
}

让我知道你是怎么办的

于 2013-07-08T13:53:57.830 回答
0

It would be as simple as:

$.getJSON('/path/to/php/server.php',
    {request: JSON.stringify({request: 'Sample'})}).done(function (data) {
    console.log(data);
});

You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.

于 2013-07-08T13:42:35.590 回答
-1

你走在正确的道路上;PHP 输出一个结果,您使用 AJAX 来获得该结果。当您在浏览器中查看它时,由于您的浏览器对 JSON 数据的解释,它自然会向您显示 HTML 结果。

要将这些数据导入 JavaScript,请使用jQuery.get()

$.get('output.html', function(data) {
  var importedData = data;
  console.log('Shiny daya: ' + importedData);
});
于 2013-07-08T13:40:27.243 回答