Calling function

0

I'm starting in javascript and I'm having a question. What is the best way to pass instructions to a Javascript function, I'll give a current example of the way I'm doing, it works, but is it a good practice?

sistema('/comando2'); //estou chamando assim



        sistema(cmd)
        {  if((req.state == 4) && (req.status == 200))//verifica a request do XMLHttpRequest
            {   
                if(cmd.search("/comando1")>=0) {faz algo//}
                if(cmd.search("/comando2")>=0) {faz algo//}

                }

        }

I would also like to know a good practice to create a request function with XMLHttpRequest, in which I change the URL parameter and values according to the need, and treat errors correctly.

Thank you

    
asked by anonymous 11.10.2017 / 05:43

1 answer

1

To use .search you need to pass a RegExp . In your example you are passing a String .

As your input is a String, then you can use .includes() or indexOf .

So it could stay:

function sistema(cmd) {
  if (cmd.includes("/comando1")) {
    console.log(1);
  }
  if (cmd.includes("/comando2")) {
    console.log(2);
  }
}

sistema('/comando2');
sistema('/comando2');
sistema('/comando1');

I do not quite understand how you want to use req.state in this function because it belongs to ajax and that code is not in the question because it is probably not related to the problem. So I removed that from the answer and focused only on the issue of detecting the right command.

    
11.10.2017 / 10:52