开发者

Parse javascript to php

This is my first post and every opinion/help will be much appreciated by me.

I am new to php and javascript. So lets start...

What i want to do is parse a variable to an external php form every time a person clicks on text. For example lets assume that i have the following string echoed $test = "what a beautiful day"; I 开发者_如何学JAVAwant when a person clicks on "what" the "phpquery?test=what" to be triggered. From what i have read javascript can help with that because of the client side scripting logic Thank you all in advance!


This is usually handed via XMLHttpRequest, usually abstracted via a library that irons out the differences between browsers (bigger libraries that do lots of other stuff include YUI and jQuery).


I would parse the sentence in such a way that each word is encapsulated in a tag. For example:

<span class="clickable">What</span> <span class="clickable">a</span> <span class="clickable">wonderful</span> <span class="clickable">day</span>

than you can bind a click function to each of these spans like so using JQuery

$(document).ready(function() {
    $("span.clickable").bind("click", function() {
          var wordClicked = $(this).html();
          $.get("phpquery?word=" + wordClicked );
    }); 
});

and do as SalmanPK suggested and use the $.get to send the word click to PHP :)

HTH


Yes you will have to do that using AJAX.

Have a look at jQuery, its very easy to learn for newbies.

You can accomplish this with jQuery using this simple piece of code:-

$('a').click(function(){  // You can use a css selector to select your anchor tag
    $.get("phpquery?test=what");
});


Ofcourse in most cases XMLHttpRequest would be suitable, but maybe you prefer the simple solution:

window.location.search = "?test=what";


here is an example of how you could achieve the click handling with jQuery, and also how you can do an ajax call (commented out after alert)

http://jsfiddle.net/UgXAH/1/

HTML:

<p class="interactive">this is some text</p>

Javascript:

$().ready(function(){
    var textArray = $('.interactive').text().split(' ')
    $('.interactive').empty()
    $(textArray).each(function(){
        var textItem = $('<span>'+this+' </span>')
        textItem.click(function(){
            var text = $(this).text()
            alert('fire off ajax request with text='+text)            
            /*$.ajax({
                url:'some-url.php',
                data:{
                    text:text
                }      
            })*/
        })
        $('.interactive').append(textItem)
    })
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜