Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

php - Echo a single variable returned in data object via AJAX Success

I realize this is close to other questions. I simply can;t find the answer.

I have an onclick event that successfully fires an AJAX POST to PHP. The Data are returned successfully in an encoded_json array.


function upvote(str,str2) {
---do a bunch of stuff  
    }
    jQuery.ajax({
    type: 'POST',
    url: MyAjax.ajaxurl,
    data: {"action": "post_my func", "voted_item":theItemid,"vote_value":currentvote, "vote_type":"upvote"},

    success: function(data){
    var result = JSON.parse(data);
    console.log(data)
    //console.log(result[2])
    //alert(result[2]);
    jQuery('#newtexthere').html(data);  
    
        }                 
    });     
}

I can echo it. I know it's there. The console.log(data) and console.log(result) look like this:

{"rowcount":"18","result":"6"}

All I want to do is echo a part of this array in #newtexthere as in

<p id="newtexthere">
*18*
</p>

Any and all help would be most appreciated!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're extremely close. You need to access the individual properties of the result object. You can do so by placing a period after the object name and then specifying a property.

jQuery('#newtexthere').html(result.rowcount);  

Note: this only works after you parse the JSON.

In your sample, you try to access the data with array syntax (result[2]) which won't work here because the result variable is an "object" which for now is essentially a group of variables. Accessing object properties is typically done with a period in JS, though you could also get to it with result['rowcount'], though most people will typically use the dot syntax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...