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
216 views
in Technique[技术] by (71.8m points)

php - Learning how to use AJAX with CodeIgniter

It's kind of embarassing that I find it so difficult to learn JavaScript, but ..

Let's say I have a really simple controller like this:

class front extends Controller {

    public function __construct()
    {
        parent::Controller();   
    }

    public function index()
    {
        //nothing!
    }

    public function test () {

        $someNumber = $this->input->post('someNumber');

        if ($someNumber == 12) { return TRUE; }

    }

}

Yes, that could probably be written better, haha.

What I want to know is - how could I use JavaScript to submit a number in a form (I'll worry about validation and models later), how should I write my test() function so that it returns something readable by the JavaScript (I'm assuming return TRUE probably wouldn't work, perhaps XML or JSON or something like that?), and how do I access the data with the JavaScript?

I know there are frameworks like jQuery that will help with this, but right now I'd just like to understand it at the simplest level and all the tutorials and guides I've found so far are way too in depth for me. An example in jQuery or whatever would be good too.

Thanks a lot :)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

you would just print it out basically, and re-capture that information via javascript:

public function test() {
    $somenumber = $this->input->post('someNumber');
    if ($somenumber == 12) {
        print "Number is 12";
    } else {
        print "Number is not 12";
    }
}

your javascript might look something like this:

var xhr;
xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        // this is where the return information is
        alert('Status: '+xhr.status+' Response: '+xhr.responseText);
    }
}

xhr.open('POST', '/front/test');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('someNumber=12');

the code above doesn't take into account browser specific issues, but should run on firefox/ie7 at least i believe.

here's a jQuery example of all the above:

var options = {
    'someNumber' : 12
}

$.post('/front/test', options, function(data) {
    alert(data); // should print "Number is 12"
});

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

...