带有json的ajax如何

I try AJAX and JSON. I have got this very simple scripts. Could you help me to get it work?

html file

               <div class="esemeny">
                <h2>Event</h2>
                <p></p>
                <button>click</button>
                </div>

json file, I call it eventresult.json

                {name: whatever,
                }

and the javascript file

$(function(){
          $('button').on('click', function(){
          $.ajax('/javascript/eventresult.json', {
          dataType: 'json',
          success: function(result){
          var esemeny = $('.esemeny');
          esemeny.find('p').html(result.name);
          }
       });
    });
 });

Thank you

I guess your JSON should look like

{
   name: "whatever"
}

Mind the double quotes and the unnecessary comma.

Well,you actually didn't descripte the question clearly.You can have a debug that can be seen from your firebug console,like this:

$.ajax('/javascript/eventresult.json', {
      dataType: 'json',
      success: function(result){
      var esemeny = $('.esemeny');
      esemeny.find('p').html(result.name);
      }
   }).fail(function(jqXHR, textStatus, errorThrown){console.log(textStatus+':'+ errorThrown)})

You didn't tell what did want to do exactly, anyway I think, this what you want to do: JSON:

{
   name: "whatever"
}

JS:

$(function(){
          $('button').on('click', function(){
          $.ajax('/javascript/eventresult.json', {
          dataType: 'json',
          type: 'GET' // you want to get content 
          success: function(result){
          var esemeny = $('.esemeny');
          esemeny.find('p').html(result.name);
          }
       });
    });
 });

Hope that helps a bit

Here are some suggestions that should make it work:

  • Make sure you include the necessary script files in your html file:

<head>
  <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>

<div class="esemeny">
  <h2>Event</h2>
  <p></p>
  <button>click</button>
</div>

<script src="javascript.js"></script>

  • Make sure you use valid json in the json file

{ "name": "whatever" }

  • Use .click() function in your javascript:

$(function() {

  $('button').click(function() {

    $.ajax('/trials/eventresult.json', {

      dataType: 'json',

      success: function(result) {

        var esemeny = $('.esemeny');

        esemeny.find('p').html(result.name);

      }

    });

  });

});

</div>