简体   繁体   中英

Use AJAX to load content to a jQuery UI dialog

On my site, I have a bunch of profile previews that are being generated by running JSON data through a mustache.js template.

Here's the template:

<script id="profile-preview-template" type="text/template"> 
    <div class="col-sm-3">
        <a style="display:block">
            <div class="profile-preview">
                <img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
                <h1>{{first_name}} {{last_name}}</h1>
                <h2 class="text-muted">{{major}}</h2>
                <h3 class="text-muted">Cohort {{cohort}}</h3>
            </div>
        </a>
    </div>
</script> 

The profile preview shows select info from the JSON info like first_name , last_name , etc.

Here's the format of the JSON data:

{
"profiles": [
{
  "first_name": "Robert",
  "last_name": "Hosking",
  "img_url": "img/about/hackbert.jpg",
  "major": "Computer Science",
  "cohort": 12,
  "bio": "some info",
  "linkedin": "some url",
  "home_town": "some place",
  "status": "Student"
},
{
  "first_name": "Jimmy",
  "last_name": "Harval",
  "img_url": "img/about/hackbert.jpg",
  "major": "Chemistry",
  "cohort": 13,
  "bio": "some info",
  "linkedin": "some url",
  "home_town": "some place",
  "status": "Student"
}
]
}

However, when one of the previews is clicked, I'd like to make a jQuery UI dialog modal popup containing all of the info in the JSON data (not just the data displayed in the preview).

My question is how do I get a reference as to which profile preview was clicked so I know where in the JSON file to look to get the rest of the information.

In your template, give each <a> element an id attribute equal to the index of the corresponding profile in the JSON array.

Then, you can give the <a> element an onclick method such as foo(this) , because this will pass the element to the function. In your function, you can retrieve the id with $(elem).attr("id") , where elem is the function parameter. Now you have the index of the profile, so it should be easy to retrieve the profile's information.

I made some slight changes to your HTML and template script.

<div class="profile-full"></div>
<div class="preview"></div>
<script id="profile-preview-template" type="text/template"> 
    <div class="col-sm-3">
        <a style="display:block">
            <div class="profile-preview">
                {{#profiles}}
                <img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
                <h1 id="whichProfile">{{first_name}} {{last_name}}</h1>
                <h2 class="text-muted">{{major}}</h2>
                <h3 class="text-muted">Cohort {{cohort}}</h3>
                {{/profiles}}
            </div>
        </a>
    </div>
</script>

As you can see, 2 divs for demonstration purposes.

  • .profile-full Where the contents of the correct object is output using JSON stringify. What gets output can of course be changed, this is just to show that the correct object is selected.
  • .preview Where the preview profiles are generated.

I also added the opening and closing {{#profiles}} {{/profiles}}

profile is derived from what is set in the beginning of your json.

"profiles": [

We assume that you have correctly linked the jQuery and mustache.js libraries. Name your json file from your post as data.json You must also link the .js file below. I have named it main.js.

$(function()    {

  $.getJSON('data.json', function(data)  {
    var template = $('#profile-preview-template').html();
      var html = Mustache.to_html(template, data);
    $('.preview').html(html);

    allProfiles = data.profiles;
    lookup = [];
    for(i=0;i<data.profiles.length;i++) {
      lookup.push(data.profiles[i].last_name);
    };

  });//getJSON

  $(document).on('click', '#whichProfile', function() {
    var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
    var i = jQuery.inArray(whichName, lookup);
    $('.profile-full').html(JSON.stringify(allProfiles[i]));
  });

});//document ready

So what's happening here?

$(function()    {

  $.getJSON('data.json', function(data)  {
    var template = $('#profile-preview-template').html();
      var html = Mustache.to_html(template, data);
    $('.preview').html(html);

After our document.ready shorthand, we GET the contents of the data.json, and hold it in data. Then we put the contents of html into the div with a class of preview, as we have formatted it according to the template script.

    allProfiles = data.profiles;
    lookup = [];
    for(i=0;i<data.profiles.length;i++) {
      lookup.push(data.profiles[i].last_name);
    };

  });//getJSON

Next we'll create an array called lookup which contains only the last_name data from our json. This will make it possible and fast to get the reference as to which profile preview was clicked. If you only have a few names, using the last name is fine, but use a unique identifier if the amount of profiles grows (So overlapping last names doesn't occur). Consider adding a unique id, or email to your json.data.

Then close your getJSON.

  $(document).on('click', '#whichProfile', function() {
    var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
    var i = jQuery.inArray(whichName, lookup);
    $('.profile-full').html(JSON.stringify(allProfiles[i]));
  });

});//document ready

Here on clicking a name will get the .text of what's on our page. We will convert it so it's only the last name (strip everything before the space). We then search for this last name within the lookup array and return its index. Now that we have this index we can use it to get any value within the json relative to the index. In this example we just put the entire stringified contents of the relevant object into our profile-full div

Finally we close our document.ready.

Try clicking on a name (Can be the first or last name). We could of course put anything from that relevant object anywhere else. For example: remove the line

$('.profile-full').html(JSON.stringify(allProfiles[i]));

and replace it with

alert(allProfiles[i].first_name + ' ' + allProfiles[i].last_name + 
  ' is studying ' + allProfiles[i].major + ' as their Major');

Now clicking on a name will get a pop up, stating their full name and which Major they are studying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM