简体   繁体   English

更新动态创建的对象值而无需刷新页面

[英]Update dynamically created object value without page refresh

This maybe a stupid question (it's not true that there are no stupid questions).. but here goes. 这可能是一个愚蠢的问题(并非没有愚蠢的问题是不对的)..但是这里有。 I will lay out what I'm doing: 我将列出我在做什么:

1) user logs into a page and the first that that happens is that a list of objects from a MySQL database is pulled using php. 1)用户登录到页面,首先发生的是使用php从MySQL数据库中提取对象列表。 it's returning an array of objects via json_encode(). 它通过json_encode()返回一个对象数组。

Then the page dynamically builds a DOM element for each object and is appended into a container via jQuery $('container').append(.....>. This happens through a loop and a php variable that gets assigned as a javascript variable.. the important parts of the code: 然后页面为每个对象动态构建一个DOM元素,并通过jQuery $('container')。append(.....>。追加到容器中。这是通过循环和被分配为javascript的php变量发生的变量..代码的重要部分:

 for(var i = 0, len = userObjects.length; i < len; i++){
     var currentObject = userObjectsObjects[i];
     var isCurrentFavorite = isFavorite(currentObject.isFavorite);

     var ratings = buildRatingString(currentObject.ratings, currentObject.raters);

    if(count % 4 !=0){
        $(".content").append('<div class=col-md-3>.............');   
        count++;
    }else if(count % 4 == 0){
        $(".content").append('<div class=col-md-3>........');
        count++;
    }
    $(".content").append('</div></div>');
}

This builds a DOM element and places the corresponding currentObject. 这将构建一个DOM元素并放置相应的currentObject。 into the proper place and displays it on the page. 放入适当的位置并显示在页面上。

All of that is fine and dandy. 所有的一切都很好。 Not ideal (i'm open to suggestions on how to optimize that process because it seems convoluted to me), but it works. 这并不理想(我愿意就如何优化该过程提出建议,因为在我看来这很令人费解),但它确实可行。

My issue: 我的问题:

A user can click on a heart to add to their favorites. 用户可以单击心脏以添加到他们的收藏夹。 The click hits a function where a check is done to see if the object is currently favorited and takes appropriate action with the ajax call. 单击将击中一个函数,在该函数中进行检查以查看该对象当前是否被收藏,并通过ajax调用采取适当的操作。

Currently the only way I know how to get the objectId is by setting it as the id for the Favorites button. 当前,我知道如何获取objectId的唯一方法是将其设置为“收藏夹”按钮的ID。 When the button (which is hidden and the heart icon is in it's place) is clicked, it send that information to the function toggleFavorites() and the information is sent to the database.. ie.. 单击按钮(已隐藏并且心脏图标在其位置)时,它将信息发送到函数toggleFavorites()并将信息发送到数据库。

<button type="button" id="'+currentObject.objectId+'"></button>  

The code: (objId is the assigned id from the button above ^^^^^) 代码:(objId是从^^^^^上方的按钮分配的ID)

function toggleFavorite(objId, isFav){
var value = isFav;
var objectId= objId;

    var toTable = '';
    if(value == 'Y'){
        toTable = 'N';
    }else if(value == 'N'){
        toTable = 'Y';
    }
ajaxIt(toTable, recipeId);
    function ajaxIt(toTable, objectId){
                $.ajax({
                        type: 'post',
                        url: '../PHP/update_favorite.php',        
                        data: {isFavorite: toTable, objectId: objectId},      
                        success: function(){
                             if($('#heart' + objectId).hasClass("redClass")){
                                    $('#heart' + objectId).addClass('grayClass')                                      
                                    $('#heart' + objectId).removeClass("redClass");

                                }else if($('#heart' + objectId).hasClass("grayClass")){
                                    $('#heart' + objectId).removeClass("grayClass");
                                    $('#heart' + objectId).addClass('redClass');


**I WANT TO UPDATE THE OBJECT IN HERE**
                                }  

                }
            });
    return false;        
    }

}

This variable is set depending on if the object is currently a favorite.. ie. 根据对象当前是否为收藏夹来设置此变量。 at the time of the initial object pull. 初始对象拉动时。 so, if it's currently a favorite and the user clicks the heart.. var toTable would = 'N' (remove from favorites).. and vice versa. 因此,如果当前是收藏夹,并且用户单击心脏。.var toTable将='N'(从收藏夹中删除)..反之亦然。

I am manually setting the heart color in the ajax success function, but I need to change the actual object because I have ran into this issue: 我在ajax成功函数中手动设置了心脏颜色,但是由于遇到了这个问题,我需要更改实际对象:

If the object is currently a favorite it is denoted by isFavorite: 'Y' when the object is pulled. 如果该对象当前是收藏夹,则在将其拉出时用isFavorite:'Y'表示。 You click the heart and ajax correctly sends a 'N' to the table.. i have confirmed that works. 您单击心脏,并且ajax正确地向表发送了“ N”。 And the heart is turned from red to gray. 心脏从红色变成灰色。 If you click the heart to add to favorites again without page refresh isFavorite is still 'Y' (a new object was not pulled with the updated table values) and it sends a 'N' to the table still. 如果单击心脏以再次添加到收藏夹而不进行页面刷新,则isFavorite仍为“ Y”(未使用更新的表值提取新对象),并且仍将“ N”发送到表。

Is it possible update a dynamically created object like this so that when the toggleFavorite() function is called, it has the correct table values? 是否可以像这样更新动态创建的对象,以便在调用toggleFavorite()函数时,它具有正确的表值?

Sorry this was so wordy... I don't have the programming knowledge or vocabulary yet to be more succinct. 抱歉,这太罗word了……我还没有编程知识或词汇,但更简洁了。

The implementation that you have is actually convoluted and can be simplified using any front-end framework like angular 1/2/4/5 or reactjs or others. 您拥有的实现实际上是复杂的,可以使用任何前端框架(例如angular 1/2/4/5或reactjs或其他)简化。

For using plain JQuery, you should update the object instead of updating the DOM. 对于使用普通的JQuery,您应该更新对象而不是更新DOM。 After updating the object, you already know which DOM corresponding to the id you have to update and update the same. 更新对象后,您已经知道与该ID对应的DOM,并且必须对其进行更新。 Or make a function which will take new object and re-render the whole DOM part. 或制作一个将使用新对象并重新渲染整个DOM部分的函数。 First is preferable. 首先是优选的。 I know this is just some pseudo logic but this is so simple that it should not require any explanation. 我知道这只是一些伪逻辑,但是它是如此简单以至于不需要任何解释。 I will be happy to chat to explain more. 我很乐意聊天以解释更多信息。 Also if you use a framework, it'd be dead simple. 同样,如果您使用框架,那将变得非常简单。 Just try looking at any framework hello world example. 只需尝试查看任何框架的hello world示例即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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